【问题标题】:Doing Eager Loading and Projection in Linq to Entities在 Linq 中对实体进行 Eager Loading 和 Projection
【发布时间】:2010-07-27 19:41:34
【问题描述】:

这是我几天前发布的另一个问题的衍生,该问题已成功回答,但它确实没有涉及我遇到的潜在问题,但无法在我的原始查询中完全表达。

我有一个表产品。 Product 以一对多的关系与 ProductDescription 相关。每个产品的 ProductDescription 可以有不止一行。如果产品描述有多个翻译,它将有多个行。产品与语言是多对一的关系。 Language 有一个语言代码(en、es 等)以及一个 LanguageId(也可以在 ProductDescription 中找到)。

我想让我的用户能够请求产品并进一步告诉应用程序只返回特定语言的产品描述。

我遇到的问题是我知道我需要使用投影来完成此问题第 3 段中的任务。像这样的:

    var query = inventoryRepository.Products
                        .Where(wherePredicate)
                        .Select( a=> new Product
                        {
                            ProductDescriptions = inventoryRepository.ObjectContext.ProductDescriptions
                               .Where(a => a.Languages.AlternateCode.Equals("en", StringComparison.CurrentCultureIgnoreCase))
                        });

但是,除了语言部分之外,我在 Products 表中还有 4 个 Products 的其他子表需要为结果集加载大约 15 个属性。有什么方法可以让我进行急切加载和投影,这样我就不必手动映射所有这些属性和子对象?这是我的代码现在所在的位置:

var query = inventoryRepository.ObjectSet
                    .Include("ProductDescriptions")
                    .Include("ProductAllowedWarehouses")
                    .Include("ProductToCategories")
                    .Include("PriceLevels")
                    .Include("AttachmentAssociations.Attachment").AsExpandable()
                    .Where(wherePredicate);

无需选择,这非常好。将 ProductDescriptions 更改为投影后,我添加了一个 Select,然后我不会免费填充任何其他属性/子项。

【问题讨论】:

    标签: c# linq-to-entities projection eager-loading


    【解决方案1】:

    我会读这个blog 关于预测+热切加载。当涉及到急切加载时,您会遇到问题。建议使用 .Any 并执行子选择。

    为什么不能在 ProductDescriptions 上添加过滤器/位置?

     var query = inventoryRepository.ObjectSet
                    .Include("ProductDescriptions")
                    .Include("ProductAllowedWarehouses")
                    .Include("ProductToCategories")
                    .Include("PriceLevels")
                    .Include("AttachmentAssociations.Attachment").AsExpandable()
                    .Where(wherePredicate)
                    .Where(a=>a.ProductDescriptions.Languages.AlternateCode.Equals("en", StringComparison.CurrentCultureIgnoreCase);
    

    【讨论】:

    • 我不知道我可以堆叠两个像这样的地方。这会改变 Product 结果集吗?例如,如果我得到产品 ID 1、2、3 和 4,而只有 1、2 和 3 有“en”翻译,我仍然想退回产品 4。我只会退回没有“en”翻译的产品 4。跨度>
    • 执行此操作以转储 SQl。 (查询为 ObjectQuery).ToTraceString();它会将 sql 转储到输出窗口。
    • 它只是构建了一个 IQueryable,所以它会将最终的 where 追加到查询中,所以它必须满足条件,也就是必须是“EN”
    • 我在那个博客上没有看到任何关于结合预先加载和投影的信息。
    • 第一段谈到预测会扼杀渴望加载。
    猜你喜欢
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    相关资源
    最近更新 更多