【问题标题】:Entitiy Framework object tree loading实体框架对象树加载
【发布时间】:2010-01-19 20:43:19
【问题描述】:

如何加载以下 EF 实体:

图片来源: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);

我得到错误:

指定的包含路径无效。

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

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您可以通过用“.”分隔关系来加载树

    context.Address.Include("Person.Pets"); //Include all the persons with their pets
    context.Pets.Include("Person.Address"); //Include all the persons with their addresses
    

    【讨论】:

      【解决方案2】:

      始终从顶层对象向下选择,例如:

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

      【讨论】:

      • 假设我想通过地址实体加载对象。
      • 您可能可以通过破坏 LINQ 来做到这一点,但这会令人困惑。 Pets 和 Address 之间的关系是 Person。你不能有你的蛋糕和它呢!只需要遍历“person.Address”,就可以得到每个地址的Person和Pet
      猜你喜欢
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多