实体框架对象树加载

时间:2010-01-19 10:25:33

标签: c# entity-framework

如何加载以下EF实体:

alt text

图片来源:http://blogs.microsoft.co.il/blogs/idof/archive/2008/08/20/entity-framework-and-lazy-loading.aspx

假设我们有地址ID,我们想加载人和宠物的地址。怎么做?

我们可以做到

var address = contex.Addresses.Include("Peson").Where(add => add.Id == GivenId);

但它会加载地址和没有宠物的人。

如果我包含宠物实体,请执行以下操作:

var address = contex.Addresses.Include("Peson").Include("Pets").Where(add => add.Id == GivenId);

我收到错误:

指定的包含路径无效。

所以问题是如何加载整个实体树。

2 个答案:

答案 0 :(得分:5)

您可以通过将关系与“。”

分开来加载树
context.Address.Include("Person.Pets"); //Include all the persons with their pets
context.Pets.Include("Person.Address"); //Include all the persons with their addresses

答案 1 :(得分:2)

始终从顶级对象中选择,例如:

var person = from p in context.Person.Include("Pets").Include("Address")
where p.Address.Id == givenId
select p;