如何加载嵌套的实体框架对象有效 [英] How to load nested Entity Framework objects efficiently

查看:139
本文介绍了如何加载嵌套的实体框架对象有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用实体框架

类别,子类别和产品
以下类别代码到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();

这篇关于如何加载嵌套的实体框架对象有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆