1

我每次都用稍微不同的 WHERE 部分重复以下 linq 代码。

我想遵循 DRY 原则,只指定一次视图模型。有没有办法重用相同的查询并动态指定 WHERE 条件?

我在这里查看了 SO 并遇到了一些类似的问题,但我找不到对我有意义的答案。我错过了一些明显的东西吗?

第一个例子

List<CMSSummary> summaryList = db.CMSUpdates
    .Where(i => i.PublishDate.Year == year)  // only this line is different
    .AsEnumerable().Select(i => new CMSSummary
    {
        CMSObjectID = i.CMSObjectID,
        Title = i.Title,
        SubTitle = i.PublishDate.ToString("ddd dd MMM"),
        ToolTip = i.Title,
        Summary = i.Summary,
        MainImage = i.MainImage,
        ItemURL = i.URL,
        FullURL = "/mockup/cmspage/" + i.URL,
        HTMLClasses = ""
    }).ToList();
return summaryList;

第二个例子

List<CMSSummary> summaryList = db.CMSUpdates
    .Where(i => i.Content.Contains(searchTerm))  // only this line is different
    .AsEnumerable().Select(i => new CMSSummary
    {
        CMSObjectID = i.CMSObjectID,
        Title = i.Title,
        SubTitle = i.PublishDate.ToString("ddd dd MMM"),
        ToolTip = i.Title,
        Summary = i.Summary,
        MainImage = i.MainImage,
        ItemURL = i.URL,
        FullURL = "/mockup/cmspage/" + i.URL,
        HTMLClasses = ""
    }).ToList();
return summaryList;
4

1 回答 1

3

(注意:这段代码我没有测试(准备太多),所以可能会有一些错误)

你有两个选择。

第一个是使用扩展方法接受作为谓词Where事实。Expression<Func<CMSUpdate, bool>>因此,您只需要创建自己的方法来接受Expression<Func<CMSUpdate, bool>>作为参数并使用该参数来构建查询:

List<CMSSummary> SummaryList(Expression<Func<CMSUpdate, bool>> predicate){
    return db.CMSUpdates.Where(predicate)
    .AsEnumerable().Select(i => new CMSSummary
            {
            CMSObjectID = i.CMSObjectID,
            Title = i.Title,
            SubTitle = i.PublishDate.ToString("ddd dd MMM"),
            ToolTip = i.Title,
            Summary = i.Summary,
            MainImage = i.MainImage,
            ItemURL = i.URL,
            FullURL = "/mockup/cmspage/" + i.URL,
            HTMLClasses = ""
            }).ToList();
}

并用谓词调用它:

SummaryList(i => i.PublishDate.Year == year)
SummaryList(i => i.Content.Contains(searchTerm))

(您可能需要将其更改db为作为参数传递)。

Where另一种选择是使用扩展方法返回的事实IQueryable<CMSUpdate>,并创建一个从方法中获取它IQueryable<CMSUpdate>Where方法并将查询的其余部分应用于它:

List<CMSSummary> ToSummaryList(IQueryable<CMSUpdate> query){
    return query.AsEnumerable().Select(i => new CMSSummary
                {
                CMSObjectID = i.CMSObjectID,
                Title = i.Title,
                SubTitle = i.PublishDate.ToString("ddd dd MMM"),
                ToolTip = i.Title,
                Summary = i.Summary,
                MainImage = i.MainImage,
                ItemURL = i.URL,
                FullURL = "/mockup/cmspage/" + i.URL,
                HTMLClasses = ""
                }).ToList();
}

并用半查询调用它:

ToSummaryList(db.CMSUpdates.Where(i => i.PublishDate.Year == year))
ToSummaryList(db.CMSUpdates.Where(i => i.Content.Contains(searchTerm)))
于 2013-10-12T16:08:38.570 回答