Linq查询语法与PredicateBuilder?

时间:2014-10-22 13:11:59

标签: c# linq

是否可以将PredicateBuilder与LINQ查询语法一起使用?例如,构建具有许多可选参数的基本搜索方法。如何根据我构建的谓词添加where子句?

public List<Entities.ProjectSearchResult> GetProjects(string projectName, 
                                                  string projectLaunchName, 
                                                  int? projectID, int? categoryID,
                                                  int? subCategoryID)
{
    var predicate = PredicateBuilder.True<Entities.Project>();
    if (!String.IsNullOrWhiteSpace(projectName))
        predicate = predicate.And(p => p.ProjectName.Contains(projectName));
    if (!String.IsNullOrWhiteSpace(projectLaunchName))
        predicate = predicate.And(p => p.ProjectName.Contains(projectLaunchName));
    if (projectID.HasValue)
        predicate = predicate.And(p => p.ProjectId == projectID.Value);
    if (categoryID.HasValue)
        predicate = predicate.And(p => p.SectorCode == categoryID.Value);
    if (subCategoryID.HasValue)
        predicate = predicate.And(p => p.SubSectorCode == subCategoryID.Value);

    using (CHIPSDbContext db = new CHIPSDbContext())
    {
        var query = (from p in db.Projects
                     join s in db.ProjectStatus on p.ProjectStatusCode equals s.ProjectStatusCode
                     join b in db.ProjectBrands on p.ProjectId equals b.ProjectId into brandList
                     from sublist in brandList.DefaultIfEmpty()
            select new Entities.ProjectSearchResult
            {
                ProjectID = p.ProjectId,
                ProjectName = p.ProjectName,
                ProjectLaunchName = p.ProjectLaunchName,
                Status = s.ProjectStatusDesc,

            }).AsExpandable().ToList();
        return query;
     }
}

1 个答案:

答案 0 :(得分:0)

在您返回的类型上构建谓词,以便通过调用方法更清楚您过滤的内容。

var predicate = PredicateBuilder.True<Entities.ProjectSearchResult>(); // Expression with your type
if (!String.IsNullOrWhiteSpace(projectName))
    predicate = predicate.And(p => p.ProjectName.Contains(projectName));    
...
using (CHIPSDbContext db = new CHIPSDbContext())
{
    var query = (from p in db.Projects
                 join s in db.ProjectStatus on p.ProjectStatusCode equals s.ProjectStatusCode
                 join b in db.ProjectBrands on p.ProjectId equals b.ProjectId into brandList
                 from sublist in brandList.DefaultIfEmpty()
        select new Entities.ProjectSearchResult
        {
            ProjectID = p.ProjectId,
            ProjectName = p.ProjectName,
            ProjectLaunchName = p.ProjectLaunchName,
            Status = s.ProjectStatusDesc,

        })
         .Where(predicate.Expand()) // Don't forget to expand predicate
         .AsExpandable()
         .ToList();
    return query;
 }