LINQ-递归请求
我有以下数据对象:
Messages:
MessageID int,
Text string,
ParentMessageID int?
因此,记录如下:
1 | “文本1” |无效的 2 | “回复文本1”| 1 3 | “回复回复文本1” | 2
...
我需要计算一个线程中有多少条消息。如何通过 LINQ 做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 LINQ to Entities 是不可能的:您需要编写一个公用表表达式来使用 SQL 执行递归查询。这些通常很慢。
假设您始终希望从层次结构中的同一级别开始计数,最简单的解决方案是为根 id 添加一个属性,如下所示。
对于给定线程中的所有消息,线程根都是相同的。很容易对具有相同 ThreadRootId 的对象进行计数(并且比递归查询的性能要高得多)。
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.
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).不确定是否可以使用 LINQ for EF。您最好编写一个存储过程并将其映射到 EF 模型中的某个方法。
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.