实体框架和Iqueryable问题

时间:2013-11-15 17:25:14

标签: c# .net entity-framework iqueryable

给出以下基本结构

public class Project
{
    public int ProjectId {get;set;}
    ICollection<SubProject> SubProjects {get;set;}

}

public class SubProject
{
    public int SubProjectId {get;set;}
    public int SubProjectId {get;set;}
    public int PrinterId {get;set;}
    public int AgencyId {get;set;}
    public int Status
    //Oodles more  properties
}

public class ProjectSearchResult
{
   public int ProjectId {get;set;}
   public int NoOfSubProjects {get;set;}
   //Loads more properties
}

我需要获得一个项目列表以及他们拥有的子项目数量,有时是代理商,有时是打印机,有时是按状态,

而不是做下面的事情

public IQueryable<ProjectSearchResult> GetProjects(int? status, int? agencyId, int?     printerId)
{

    var projects = db.Projects.Include(x=>x.SubProjects);
    if(status.HasValue)
         return projects.Select(proj=> new ProjectSearchResult
                               {
                                  ProjectId = proj.ProjectId,
                                  NoOfSubProjects = proj.SubProjects.Count(s=>s.Status = status)

};

if(agency.HasValue)
         return projects.Select(proj=> new ProjectSearchResult
                               {
                                  ProjectId = proj.ProjectId,
                                  NoOfSubProjects = proj.SubProjects.Count(s=>s.AgencyId= agency)

};
if(printer.HasValue)
         return projects.Select(proj=> new ProjectSearchResult
                               {
                                  ProjectId = proj.ProjectId,
                                  NoOfSubProjects = proj.SubProjects.Count(s=>s.PrinterId= printer)

};

有什么方法可以让它更通用并保持为IQueryable,而不返回所有子项目并在内存中进行计数?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

public IQueryable<ProjectSearchResult> GetProjects(Expression<Func<SubProject, bool>> predicate)
{
    return
        from p in db.Projects
        select new ProjectSearchResult {
            ProjectId = p.ProjectId,
            NoOfSubProjects = p.SubProjects.Count(predicate),
        };
}

如果不明显,你可以这样做:

var projects = GetProjects(_ => _.Status == projectStatus);