【问题标题】:Loading Nested Entities / Collections with Entity Framework使用实体框架加载嵌套实体/集合
【发布时间】:2011-10-20 02:41:52
【问题描述】:

我正在尝试在一次调用中急切地加载所有相关实体或实体集合。 我的实体看起来像:

Class Person
{
    public virtual long Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

Class Employee
{
    public virtual long Id { get; set; }
    public DateTime AppointmentDate { get; set; }
    public virtual ICollection<EmployeeTitle> Titles { get; set; }
    public virtual Person Person { get; set; }
}

Class EmployeeTitle
{
    public virtual long Id { get; set; }
    public virtual bool IsCurrent { get; set; } 
    public virtual Title Title { get; set; }
}
Class Title
{
    public virtual long Id { get; set; }
    public virtual string Code { get; set; }
    public virtual string Description { get; set; }
}

我想要做的是,如果我调用一个方法来加载所有员工,结果应该包括 Person、EmployeeTitles 列表,包括 Title 中的代码和描述 我已经能够达到第三级,即获得 Employee 和 EmployeeTitle 的人员和列表。我不知道如何使用 EmployeeTitle 获取职位信息。 我得到这个的代码是:

Context.Employees.Include("Person").Include(e => e.Titles).ToList();

请说明如何实现这一点。提前致谢。

【问题讨论】:

    标签: c# entity-framework-4.1 code-first entity-relationship eager-loading


    【解决方案1】:

    你可以试试这个:

    Context.Employees
        .Include(e => e.Person)
        .Include(e => e.Titles.Select(t => t.Title))
        .ToList();
    

    Select 可以应用于集合并加载对象图中下一级的导航属性。

    【讨论】:

    • 重要提示:不要不小心对两个 lambda 表达式 .Include(x =&gt; x.Titles.Select(x =&gt; x.Title)) 使用相同的变量,否则你会得到 Cannot convert lambda expression to type 'string' because it is not a delegate type
    • 你必须有“using System.Data.Entity”,否则会显示为这个重载不存在。
    • 有没有办法使用Include(string)实现这一目标?
    • @ŞafakGür:是的,只需使用“虚线路径”:Include("Titles.Title")
    • +1 花了一段时间才终于在 Google 中找到了正确的关键字(“实体加载具有集合的相关集合”),但这很有效 :)
    【解决方案2】:

    由于这是我在谷歌搜索的第一页,我只想发布这个。

    Slauma 的回答很好。但如果您不打算实际使用列表,建议使用 Load() 而不是 ToList()。所以它会是:

        Context.Employees
            .Include(e => e.Person)
            .Include(e => e.Titles.Select(t => t.Title))
            .Load();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多