Entity Framework 4 个相关实体未加载

Entity Framework 4 related entity not loading

我使用 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);
    }
}

谁能帮我理解为什么客户没有加载,即使我明确声明要包含它?

我找到了问题的根源!恶魔在于 "let" 命令。每当我有一个 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,然后进行第二次 "go get my includes" 调用,一切正常。

// 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);