LINQ - recursive request

a 夏天 提交于 2019-12-11 05:36:53

问题


I have the following dataobject:

Messages:
MessageID int,
Text string,
ParentMessageID int?

so, records like:

1 | "Text 1" | null 2 | "Reply to Text 1" | 1 3 | "Reply to reply to text 1" | 2

...

I need to calculate how many messages in one thread. How to do it by LINQ?


回答1:


It's not possible using LINQ to Entities: you would need to write a common table expression to do the recursive query using SQL. These are quite often slow.

Assuming you always want to count from the same level in the hierarchy, your easiest solution is to add a property for the root id, like this.

Messages:
MessageID int,
Text string,
ParentMessageID int?
ThreadRootID int

The thread root is the same for all messages in a given thread. It's easy to count those that have the same ThreadRootId (and will be much more performant than a recursive query).




回答2:


Not sure it is possible to do with LINQ for EF. You'd better write a stored procedure and map it to some method at the EF model.



来源:https://stackoverflow.com/questions/9327907/linq-recursive-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!