【问题标题】:Entity Framework 4 related entity not loadingEntity Framework 4 相关实体未加载
【发布时间】:2016-10-10 14:27:54
【问题描述】:

我在 EF4 中使用查询来拉回记录并根据其中的数据通过各种其他方式(不是 EF)处理信息,因此我经常在列表中分离 EF 对象。

在这种情况下,我在 EntityFramework 4.0 中有一个未加载相关实体的查询,即使我使用的是 .Include("...") 方法。

using (MyDBEntities ctx = new MyDBEntities())
{
    ctx.ContextOptions.LazyLoadingEnabled = false;

    // Get the first X records that need to be processed
    var q = (from t in ctx.DBTables
                .Include("Customer")
             let c = t.Customer
             where t.statusID == (int)Enums.Status.PostProcessing
             && c.isActive == true
             select t
            ).Take(batchSize).ToList();

    foreach (DBTable t in q)
    {
        // this results in c == null
        Customer c = t.Customer;

        // However t.CustomerID has a value, thus I know 
        // that t links to a real Customer record
        Console.WriteLine(t.CustomerID);
    }
}

任何人都可以帮助我理解为什么客户没有加载,即使我明确声明要包含它?

【问题讨论】:

  • 什么是batchSize?当您单步执行foreach 循环时,您能看到您有多少条记录并且您能看到任何值吗?
  • batchSize 是一个 int,它会更早地传递给函数。

标签: c# entity-framework entity-framework-4


【解决方案1】:

我找到了问题的根源!恶魔在于“让”命令。每当我有一个 let 或第二个“from”子句(如连接)时,“.Includes”就会被忽略!!!

// -- THIS FAILS TO RETRIEVE CUSTOMER
// Get the first X records that need to be processed
var q = (from t in ctx.DBTables
            .Include("Customer")
         // Using a "let" like this or 
         let c = t.Customer
         // a "from" like this immediately causes my include to be ignored.
         from ca in c.CustomerAddresses
         where t.statusID == (int)Enums.Status.PostProcessing
         && c.isActive == true
         && ca.ValidAddress == true
         select t
        ).Take(batchSize).ToList();

但是,我可以在一次调用中获取我需要获取的 ID,然后进行第二次“获取我的包含”调用,一切正常。

// Get the first X record IDs that need to be processed
var q = (from t in ctx.DBTables
         let c = t.Customer
         from ca in c.CustomerAddresses
         where t.statusID == (int)Enums.Status.PostProcessing
         && c.isActive == true
         && ca.ValidAddress == true
         select t.TableID
        ).Take(batchSize).ToList();

// Now... go "deep-load" the records I need by ID
var ret = (from t in ctx.DBTables
            .Include("Customer")
           where q.Contains(t.TableID)
           select t);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2018-02-27
    • 1970-01-01
    • 2014-07-22
    • 2020-08-06
    • 2018-09-10
    相关资源
    最近更新 更多