过滤相关实体以获取值列表

时间:2015-04-09 13:49:30

标签: c# entity-framework entity-framework-6 eager-loading

我的应用程序中有以下实体类:

public class Project
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual ICollection<ProjectManager> ProjectManagers { get; set; }
}

public class Manager
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}

public class ProjectManager
{
    public virtual int ManagerId { get; set; }
    public virtual int ProjectId { get; set; }
    public virtual bool CanUpdate { get; set; }
    public virtual bool CanDelete { get; set; }
}

我正在加载当前经理的项目列表:

var projects = context.Projects.Where(
    x => x.ProjectManagers.Any(y => y.ManagerId == currentManagerId)
);

每个项目的ProjectManagers属性现在包含了所有管理员的信息,但我只想加载当前经理的记录。

我见过以下方法:

context.Entry(project)
       .Collection(x => x.ProjectManagers)
       .Query()
       .Where(x => x.ManagerId == currentManagerId)
       .Load();

但是,它需要为每个项目单独SELECT查询。可以在整个项目列表的单个查询中完成吗?

澄清:

// Sample of an existing data
var existing = new []
{
    new Project
    {
        Name = "A",
        ProjectManagers =
        {
            new ProjectManager { ManagerId = 1 },
            new ProjectManager { ManagerId = 2 },
            new ProjectManager { ManagerId = 3 }
        }
    },
    new Project
    {
        Name = "B",
        ProjectManagers =
        {
            new ProjectManager { ManagerId = 2 },
        }
    },
};

// What I want to get (in a single query!)
var desired = new []
{
    new Project
    {
        Name = "A",
        ProjectManagers =
        {
            new ProjectManager { ManagerId = 1 },
            // nobody else here
        }
    }
};

0 个答案:

没有答案