【问题标题】:How can I load a navigation property in an EF 4.0 code first entity collection?如何在 EF 4.0 代码优先实体集合中加载导航属性?
【发布时间】:2011-11-08 04:03:23
【问题描述】:

我正在使用带有 Code First 的 EF 4.0,并且我有一个 Product 实体,它有一个 ProductSpecificationAttributes 导航属性。我有一个产品实体 IList 产品的列表,我希望此列表中的所有产品都加载 ProductSpecificationAttributes,而不必为列表中的每个产品访问数据库。所以如果我有:

IList<Product> products = DbContext.ExecuteStoredProcedureList<Product>(
                "ProductLoadAllPaged", parameters here);

我想做这样的事情:

IQueryable<Product> query = products.AsQueryable().Include(
x => x.ProductSpecificationAttributes);

在尝试检索其 ProductSpecificationAttributes 时,是否有一种自动方法可以在 EF 4.0 Code First 中执行此操作,而无需为每个产品查询数据库?

您的帮助将不胜感激!

谢谢

【问题讨论】:

    标签: .net asp.net-mvc-3 entity-framework-4


    【解决方案1】:

    我只能看到类似通过产品 ID 重新查询产品的内容,包括导航集合:

    IQueryable<Product> query = context.Products
        .Include(p => p.ProductSpecificationAttributes)
        .Where(p => products.Select(p1 => p1.Id).Contains(p.Id));
    

    products.Select(p1 =&gt; p1.Id) 是内存中 Id 的集合,查询转换为 SQL IN 子句。这只是一次数据库往返。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多