使用实体框架加载嵌套实体/集合 [英] Loading Nested Entities / Collections with Entity Framework

查看:157
本文介绍了使用实体框架加载嵌套实体/集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to Eagerly load all the related entities or collection of Entity in one call. My Entities Looks like:

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; }
}

Iam想要做的是,如果我调用一种方法来加载所有雇员,则结果应包括Person,EmployeeTitles列表,包括标题中的代码和描述 我已经能够进入第三级,即,将Employee与人员和EmployeeTitle列表一起使用.我不知道如何通过EmployeeTitle获取标题信息. 我要得到的代码是:

What Iam trying to do is if i call a method to load all Employees, the result should include Person, List of EmployeeTitles including the code and description from Title I have been able to get to the third level i.e. getting the Employee with person and list of EmployeeTitle. I don't know how to get the title information with the EmployeeTitle. My code to get this is:

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

请阐明如何完成此操作.预先感谢.

Please shed some light on how to accomplish this. Thanks in advance.

推荐答案

您可以尝试以下操作:

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

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

Select can be applied to a collection and loads navigation properties of the next level in the object graph.

这篇关于使用实体框架加载嵌套实体/集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆