如何在实体框架模型中编写递归查询代码?
我有一个模型,其中包括节点和关系(通过父节点、子节点排列将节点连接在一起)。
Q1 - EF / Linq-to-entities 中是否有任何方法可以对节点(例如 context.Nodes..)执行查询以在图中查找“所有父母”或“或孩子”?
Q2 - 如果 Linq-to-entities 中没有,除了编写手动执行的方法之外,还有其他方法可以做到这一点吗?
Q3 - 如果手动是唯一的方法,那么当该方法不断递归数据时,我是否应该担心将进入数据库的数据库命中数?或者更具体地说,是否有任何 EF 缓存类型功能可以帮助确保该方法从“数据库命中数”的角度来看是性能的?
谢谢
谢谢
I have a model which includes NODES, and RELATIONSHIPS (that tie the nodes together, via a parent_node, child_node arrangement).
Q1 - Is there any way in EF / Linq-to-entities to perform a query on nodes (e.g. context.Nodes..) to find say "all parents" or "or children" in the graph?
Q2 - If there's not in Linq-to-entities, is there any other way to do this other than writing a method that manually goes through and doing it?
Q3 - If manual is the only way to do it, should I be concerned about the number of database hits that will be going out to the database as the method keeps recursing through the data? Or more specifically, is there any EF caching type feature that might assist here in ensuring the method is performance from a "number of database hits" point of view?
thanks
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有如此优雅的方法来压平一棵树。
您可以(在存储过程或实体框架中)创建一个循环,该循环将运行直到没有发生任何更改,在该迭代中您将在某个临时表或集合中绑定父级和子级的子级。
最后你将拥有父母、继承人两个人的集合。
There is no such elegant way to flaten a tree.
you can (in stored proc or in entity framework) create a loop that will run untill no change happend, in which iteration you will bind parent and child's child in some temp table or collection.
in the end you will have a collection of parents, sucsessor two-ples.
当您使用 Microsoft SQL Server 2005 或更高版本时,可以使用 CTE (通用表表达式)。它们允许您定义递归查询。虽然 SQL Server 在幕后除了为您发出一堆查询之外并没有做更多的事情,但它完全在服务器端完成此操作,因此它可以使您免于进行大量的客户端-服务器通信。
您必须使用存储过程或普通 SQL 查询来执行此操作,因为 EF 无法为您执行此操作。
When you are using Microsoft SQL Server 2005 or up, you can use CTEs (Common Table Expressions). They allow you do define a recursive query. While SQL Server under the covers doesn't do much more than firing a bunch of queries for you, it does this completely server side, so it saves you from having a lot of client-server communication.
You will have to do this using a stored proc or a normal SQL query, because there is no way EF can do this for you.