Linq不包含'Where'的定义

101*_*110 0 c# sql linq

我正在尝试通过if语句调整我的查询,如下所示:

        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;

        }
Run Code Online (Sandbox Code Playgroud)

这似乎没有给我任何错误.但是,当我尝试使用where子句进行更多过滤时,它无法识别该术语.我理解IQuerable不支持它,但有没有办法将"articles"设置为null,然后用if语句设置它?

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;
        }
Run Code Online (Sandbox Code Playgroud)

我知道我可以在一个大的if语句中执行此操作if(User.IsInRole("Admin"))然后执行所有代码然后将相同的代码复制并粘贴到不同的if语句中(if(user.IsInRole("Educator)),但我认为这种冗余且非常糟糕的编码实践.

干杯.

Jon*_*eet 9

您的articles变量使用非泛型类型IQueryable,它实际上支持很少.

你想要IQueryable<T>一个合适的<T>.例如:

IQueryable<Article> articles;
// Initialize as before
Run Code Online (Sandbox Code Playgroud)

我个人会改变你的初始化方式:

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?
}
Run Code Online (Sandbox Code Playgroud)