问题描述
我正尝试通过if语句来调整查询,如下所示:
I'm trying to adjust my query through an if statement as shown below:
IQueryable articles = null;
if (User.IsInRole("Admin"))
{
articles = from s in db.Articles
select s;
}
if (User.IsInRole("Educator"))
{
articles = from s in db.Articles
where s.createdBy == WebSecurity.CurrentUserName
select s;
}
这似乎没有给我任何错误.但是,当我尝试使用where子句进行更多过滤时,它无法识别该术语.我知道IQuerable不支持它,但是有一种方法可以将最初的文章"设置为null,然后使用if语句进行设置?
This doesn't seem to give me any errors. However, when I try to filter a bit more with a where clause it doesn't recognize the term. I understand IQuerable doesn't support it, but is there a way to originally set "articles" to null, then set it with a if statement?
if (!String.IsNullOrEmpty(searchString))
{
articles = articles.Where(s => s.title.ToUpper().Contains(searchString.ToUpper())
|| s.content.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "name_desc":
articles = articles.OrderByDescending(s => s.title);
break;
case "Date":
articles = articles.OrderBy(s => s.dateCreated);
break;
case "date_desc":
articles = articles.OrderByDescending(s => s.dateCreated);
break;
case "rating_desc":
articles = articles.OrderByDescending(s => s.finalReview);
break;
case "Rating":
articles = articles.OrderBy(s => s.finalReview);
break;
case "Views":
articles = articles.OrderBy(s=>s.numViews);
break;
case "views_desc":
articles = articles.OrderByDescending(s => s.numViews);
break;
case "Educators":
articles = articles.OrderBy(s => s.educatorCRUD);
break;
case "educators_desc":
articles = articles.OrderByDescending(s => s.educatorCRUD);
break;
default:
articles = articles.OrderBy(s => s.title);
break;
}
我知道我可以在if语句if(User.IsInRole("Admin"))中执行此操作,然后执行所有代码,然后将同一代码复制并粘贴到不同的if语句中(if(user.IsInRole("Educator )),但我认为这是多余且非常糟糕的编码做法.
I know I can do this in a big if statment if(User.IsInRole("Admin")) then execute all code then copy and paste the same code in a different if statement (if(user.IsInRole("Educator)), but I think this redundant and really bad coding practice.
干杯.
推荐答案
您的articles
变量正在使用非通用类型IQueryable
,该类型的支持实际上很少.
Your articles
variable is using the non-generic type IQueryable
, which supports very little indeed.
您想要IQueryable<T>
作为合适的<T>
.例如:
You want IQueryable<T>
for a suitable <T>
. For example:
IQueryable<Article> articles;
// Initialize as before
不过,我会亲自更改您的初始化方式:
I'd personally change how you're initializing it though:
IQueryable<Article> articles = db.Articles;
if (User.IsInRole("Admin"))
{
// No change...
}
else if (User.IsInRole("Educator"))
{
articles = articles.Where(s => s.createdBy == WebSecurity.CurrentUserName);
}
else
{
// Throw an exception? What do you want to happen if they're neither an
// educator nor an administrator?
}
这篇关于Linq不包含“哪里"的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!