如何加载嵌套的实体框架对象有效
我试图使用实体框架
类别,子类别和产品
以下类别代码到3深树装载到TreeView控件是的IQueryable<产品分类>
其中,产品分类是一个EF4.0生成的对象(默认代码生成)
Categories, SubCategories and Products
in the code below categories is an IQueryable<ProductCategory>
where ProductCategory is an EF4.0 generated object (default code generation)
子被一个FK回类别表(所以理论上我们可以去任何深度,但数据域只会有两个级别)
SubCategories is a FK back to the categories table (so in theory we could go to any depth, but the data domain will only have two levels)
var container = categories.Where(c=>c.somecondition).Include("Subcategories.Products");
foreach (var cat in container) {
addtoTree(cat);
foreach (var sub in cat.SubCategories)
{
addtoTree(sub);
foreach (var prod in sub.Products) addtoTree(prod);
}
}
这仍是发行的每个查询内循环迭代。我缺少的EF配置的东西(改变的背景下?),以阻止这种情况发生?或有写这种代码的另一种方式?
This is still issuing queries for each inner loop iteration. Am I missing something in the EF configuration (changes to the context?) to stop that happening? Or is there another way of writing this sort of code?
(至于现在一个可怕的黑客,我已经创建了一个平坦的信息SQL视图,我遍历即重新打造的嵌套对象的手......讨厌,但是快!)
(As a horrendous hack for now, I've created an SQL view that flattens the information, and I iterate that to re-build the nested objects by hand...nasty, but fast!)
尝试急切地执行查询
var container = categories
.Where(c => c.somecondition)
.Include("Subcategories.Products")
.ToList();