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?
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).