【问题标题】:EF Code first Eager loading problemEF Code first Eager 加载问题
【发布时间】:2011-04-30 06:43:17
【问题描述】:

我在 1:n 关系中有两个实体:类别和产品。

public class Category 
{
   public int CategoryID { get; set; }
   public string CategoryName { get; set; }

   public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
   public int ProductID { get; set; }
   public string ProductName { get; set; }

  public virtual Product { get; set; }
}

public class context : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

我想通过 Eager loading 加载每个类别的产品。

context.Categories.Include(c=>c.Products)

但包含不加载任何导航属性。它只接受一个名为“path”的参数类型的字符串。

【问题讨论】:

    标签: ef-code-first eager-loading


    【解决方案1】:

    您是否缺少使用方法? VS 2010 在这方面有点笨,你经常需要明确输入:

    using System.Data.Entity 
    

    ..获取可用的 lambda 包含选项。

    它不会提示您添加它,因为它已经在

    下提供了基于字符串的 Include 定义
    System.Linq
    

    .Include(x => x.MyObject) 实际上是现有linq方法的新扩展方法。

    【讨论】:

    • 我对此赞不绝口,因为这似乎并不为人所知。我认为急切加载的唯一方法是使用字符串,而字符串会导致无法正确急切加载的问题
    • 谢谢!我同意。似乎有点让人失望,把所有的东西都强类型化,然后用字符串引用它(即引发运行时错误):)
    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2023-03-12
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多