c# - 使用 Entity Framework 加载嵌套实体/集合

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

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

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 的代码和描述 我已经能够达到第三级,即获得具有人员和 EmployeeTitle 列表的 Employee。我不知道如何使用 EmployeeTitle 获取职位信息。 我的代码是:

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

请说明如何完成此操作。提前致谢。

最佳答案

你可以试试这个:

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

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

关于c# - 使用 Entity Framework 加载嵌套实体/集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6943942/

相关文章:

c# - 当外部库不向后兼容时检查属性是否存在

c# - 处理 ViewModel/Model 中的致命异常

c# - Debian 7 Linq To SQL 上的 Mono 字符串对象引用未设置为对象的实例

ef-code-first - 如何使用 Entity Framework 4 Code-First 定义数据库 View ?

c# - 如何使用 Code First Entity Framework 4.1 获取完整对象

c# - 在 "friend"程序集中隐藏内部接口(interface)

asp.net-mvc - Entity Framework 4.1 Code First - 在存储库之间共享 dbContext 的正确方法?

entity-framework-4 - Entity Framework 4 - 在持久性未知上下文中使用 CTP5(代码优先)映射非公共(public)属性

c# - 存储库/UoW - 使用还是不使用?

c# - 首先通过代码发出多个 1 对 1 关联?