【问题标题】:Entity Framework 4.1 Eager Loading on complext object实体框架 4.1 对复杂对象的渴望加载
【发布时间】:2013-01-09 17:47:25
【问题描述】:

在当前的 MVC4.0 项目中,我使用的是 Entity Framework 4.1 Database first 模型。

此结构的一部分包括以下表格

compGroupData 调查数据 二级数据

compGroupData 和 SurveyData 未加入数据库

SecondaryData 通过外键 SurveyData.surveydatakey = SecondaryData.surveydatakey 以一对一的关系加入到 SurveyData

在我的项目中,我有一个类 ComparisonWithData 定义为:

public class ComparisonWithData
{
    public compGroupData compgrp { get; set; }
    public SurveyData surveydata { get; set; }
    public ComparisonWithData()
    {
        compgrp = new compGroupData();
        surveydata = new SurveyData();
    }
}

这为我提供了特定比较组的结果集以及与之匹配的数据。

过去我曾通过以下查询为此检索数据:

    List<ComparisonWithData> comparisonwithdata  = ((from compgrp in db.compGroupDatas
                       where compgrp.grpYear == rptyear && compgrp.CompGroupID == ccompgrp.CompGrpID
                       join surveydata in db.SurveyDatas on new { compgrp.companyid, SurveyYear = (Int32)compgrp.SurveyYear } equals new { companyid = surveydata.companyid, SurveyYear = surveydata.surveyyear }
                       select new ComparisonWithData
                       {
                           compgrp = compgrp,
                           surveydata = surveydata,


                       }
                       )).ToList();

随着最近数据的变化,我现在还需要引用 SecondaryData,但由于记录的数量确实需要它来急切地加载而不是延迟加载。 (循环期间的延迟加载会导致数以千计的数据库调用)

我已经研究过在调查数据上使用“包含”方法,以及将初始查询转换为 ObjectQuery 并执行包含。

第一种方法不会急切加载,而第二种方法似乎总是返回一个空对象。

是否有一种方法可以为 SurveyData 加载 SecondaryData,或者我应该一起寻找不同的方法。

我对此的唯一限制是我无法升级到 EF5,因为我们在 .Net 4.5 上存在限制

任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: asp.net-mvc-4 entity-framework-4.1 eager-loading


    【解决方案1】:

    您可以尝试先投影到一个匿名对象中,然后在该投影中使用SecondaryData,具体化此结果,然后再次投影到您的最终结果对象中。 EF 上下文提供的自动关系修复应填充您的 ComparisonWithData 对象的导航属性 surveyData.SecondaryData(只要您未在查询中禁用更改跟踪):

    var data = (( // ... part up to select unchanged ...
               select new // anonymous object
               {
                   compgrp = compgrp,
                   surveydata = surveydata,
                   secondarydata = surveydata.SecondaryData
               }
               )).AsEnumerable();
               // part until here is DB query, the rest from here is query in memory
    
    List<ComparisonWithData> comparisonwithdata =
               (from d in data
               select new ComparisonWithData
               {
                   compgrp = d.compgrp,
                   surveydata = d.surveydata
               }
               )).ToList();
    

    【讨论】:

    • 我发现了另一篇与这篇非常相似的帖子,效果很好。唯一的区别是我没有分两步完成。在surveydata.SecondaryData中加载“secondarydata”对象时也直接加载。我希望有另一种更直接的方法,但由于这种方法有效,这是最好的答案。再次感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多