实体框架如何处理递归层次结构? Include()似乎无法使用它 [英] How does Entity Framework work with recursive hierarchies? Include() seems not to work with it

查看:114
本文介绍了实体框架如何处理递归层次结构? Include()似乎无法使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目项目有一个类别



类别 ID 名称 父母 儿童 父母儿童也是类别



当我对特定的项目进行LINQ to Entities查询时,它不会返回相关的类别,除非我使用 Include(Category)方法。但是,它的父母和孩子并没有带来完整的类别。我可以做 Include(Category.Parent),但是这个对象就像一棵树,我有一个递归层次结构,我不知道它在哪里结束。 / p>

如何使EF完全加载与父母和孩子一起的类别,父母与父母和孩子,等等?



这不是整个应用程序的东西,因为性能方面的考虑,它只需要这个特定的实体,类别。

解决方案

而不是使用 Include 方法,您可以使用加载



然后你可以为每个人做一个,并循环遍过所有的孩子,加载他们的孩子。然后通过他们的孩子做一个,等等。



您所走过的级别数量将按照您拥有的每个循环的编号进行硬编码。



以下是使用 Load 的示例: http://msdn.microsoft.com/en-us/library/bb896249.aspx


I have an Item. Item has a Category.

Category has ID, Name, Parent and Children. Parent and Children are of Category too.

When I do a LINQ to Entities query for a specific Item, it doesn't return the related Category, unless I use the Include("Category") method. But it doesn't bring the full category, with its parent and children. I could do Include("Category.Parent"), but this object is something like a tree, I have a recursive hierarchy and I don't know where it ends.

How can I make EF fully load the Category, with parent and children, and the parent with their parent and children, and so on?

This is not something for the whole application, for performance considerations it would be needed only for this specific entity, the Category.

解决方案

Instead of using the Include method you could use Load.

You could then do a for each and loop through all the children, loading their children. Then do a for each through their children, and so on.

The number of levels down you go will be hard coded in the number of for each loops you have.

Here is an example of using Load: http://msdn.microsoft.com/en-us/library/bb896249.aspx

这篇关于实体框架如何处理递归层次结构? Include()似乎无法使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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