I have an ASP.NET MVC application in C# which is a blog. In this users can post comments and comments can be made on both posts and a comment itself. This means my comment class must be recursive and this is what I have:
public class SubComment
{
[Key]
public int subCommentId { get; set; }
public string message { get; set; }
public DateTime time_posted { get; set; }
public int parent_comment_id { get; set; }
public bool read_by_parent { get; set; }
public int parentFounder_comment_id { get; set; }
public bool parentIsSub { get; set; }
public virtual List<SubComment> SubComments { get; set; }
[ForeignKey("customer")]
public string UserId { get; set; }
public Customer customer { get; set; }
}
Now the problem I am having is that when a comment is deleted any nested comments must also be removed first. As each comment has a list of comments this can go on and on and on. I am having trouble thinking of a solution as to how to implement this delete.
What I have so far is that I can find the comment that is requesting deletion and I can find all of the replies to this specific comment but what I need is all nested comments so replies to replies etc.
Here is my code for the action that is relevant:
SubComment subComment = context.SubComments.Find(id);
replies = context.SubComments
.Where(sc => sc.parent_comment_id == subComment.subCommentId && sc.parentIsSub == true)
.OrderByDescending(sc => sc.time_posted).ToList();
Can anyone help me in implementing this, any answer is appreciated.
(I had uploaded a similar question which I couldn't delete but it's closed so it cannot be and has no answer, unfortunately).
You can create a method on your SubComment class.In this method you loop through the list of SubComments (and call the same mathod recursively). When the SubComment does not have any chilren, you can delite this Subcomment.
private void RemoveComment(context as DBContext)
{
if (SubComments.Count > 0)
{
SubComment sc;
foreach (sC in SubComments)
{
sC.RemoveComment(context)
}
}
else
{
//your code to remove element
}
}