[英]Entity Framework 4 related entity not loading
我使用EF4中的查询,根据其中的数据通过各种其他方式(不是EF)来回拉记录和处理信息,因此我经常在列表中分离EF对象。
在这种情况下,即使我使用的是.Include(“ ...”)方法,在EntityFramework 4.0中我也没有加载相关实体的查询。
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,然后再进行第二次“获取我的包含”调用,一切正常。
// 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.