【问题标题】:EntityFramework Include (Eager Load) virtual Property of virtual property [duplicate]EntityFramework 包含(急切加载)虚拟属性的虚拟属性 [重复]
【发布时间】:2017-04-14 10:53:39
【问题描述】:

假设我们有如下三个 Dbset:

Category
{
...
   public virtual ICollection<Item> Items {get; set;}
...
}

Item
{
...
   public virtual ICollection<Specification> Specifications{get; set;}
...
}

Specification
{
...
}

对于急切加载,我这样使用它:

Category cat = db.Categories.Include(c=> c.Items).FirstOrDefault(c=> c.Id == 1);

但现在的问题是

cat.Items[0].Specificationsnull,我们怎样才能使其也能立即加载集合的子集合?

P.S.:我尝试删除 virtual 关键字进行测试(我不想删除它)但它也不起作用。

【问题讨论】:

  • 如果你在 VS 中为Include 方法执行Go To Definition,你会发现一个完整的帮助主题描述了不同的Include 场景。基本上你需要使用Selects 向下导航。
  • 你可以使用其他的Include。将字符串作为参数的那个。然后你可以这样做:Include("Items.Specifications")

标签: c# asp.net asp.net-mvc entity-framework


【解决方案1】:

你也可以使用符号

db.Categories.Include("Items.Specifications")

注意必须是字符串

【讨论】:

  • 如果重命名“Items”或“Specifications”属性,Visual Studio 将不会重构此字符串。
  • @MariusOrha 这是另一个问题。事实上,马克的解决方案会奏效
【解决方案2】:
 Category cat = db.Categories
        .Include(c => c.Items.Select(s => s.Specifications))
        .FirstOrDefault(c => c.Id == 1);

【讨论】:

  • 只是想明确一点,虚拟与问题无关。
  • 是的,Select 部分负责。
【解决方案3】:

现在我们也可以使用:

db.Categories.Include(c => c.Items)
             .ThenInclude(i => i.Specifications);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多