I am new to this recursion in both SQL and Entity Framework (ADO.NET Entity Mapping). I'm working on managing comments, where I have a Comments table, and the table contains the columns NewsID, CommentID, ParentCommentID, IndentLevel, CreatedTime .
I am trying to get a list of comments for a specific news item, where all the comments are ordered according to the child under the parent and created time, as shown below:
CommentID | time | ParentCommentID Guid1 | t1 | null Guid4 | t4 | Guid1 Guid2 | t2 | null Guid3 | t3 | Guid2
Priority should be given to the parent relationship with the child, and then the time created.
So far I cant (from internet resources and previous stackoverflow Q / A)
- As shown, these recursive queries are slow. and doing it with the Entity Framework is even slower. But it can be achieved.
- So, you can do this by creating a stored procedure in SQL Server and invoking it using functional import. Another thing is to use Linq in the Entity Framework.
- In SQL Server, it is used in this format.
SQL:
WITH cte_name ( column_name [,...n] ) AS ( CTE_query_definition β- Anchor member is defined. UNION ALL CTE_query_definition β- Recursive member is defined referencing cte_name. )
- But before trying this, I want to try Linq.
For this, I refer to this link, where I have an idea: https://stackoverflow.com/a/165389/
But I tried to understand the code, but in vain. Can someone give me a better and more detailed explanation about writing a recursive CTE in the Entity Framework?
private IEnumerable<NewsComment> ArrangeComments(IEnumerable<NewsComment> commentsList, string parentNewsComntID, int level) { Guid parentNewsCommentID; if (parentNewsComntID != null) { parentNewsCommentID = new Guid(parentNewsComntID); } else parentNewsCommentID = Guid.Empty; return commentsList.Where(x => x.ParentCommentID == parentNewsCommentID).SelectMany(x => new[] { x }.Concat(ArrangeComments(commentsList, x.NewsCommentID.ToString(), level + 1)); }
And I use this, as shown below, inside the method:
return ArrangeComments(commentList,null , 0);
I tried them, and it seems like I'm not going anywhere. Although there are explanations for SQL recursion, there are fewer examples for Linq and are clear to me due to less familiarity. Can someone help me understand this CTE recursion in Linq which is great
Thank you in advance