EF Core - How to setup many-to-many for same entity that already has a one-to-many relationship

c# entity-framework entity-framework-core

Question

I currently have a one-to-many relationship between a Post and Comment. One Post can contain multiple Comments. What I want to do is create a many-to-many relationship for Comments. I also have a one-to-many relationship between User and Comment.

I.e. each Comment should be able to contain a collection of Comment. E.g. a user can comment on another user's comment. I want to preserve the ordering of comments so that I can display them in the correct order.

public class Comment
    {
        [Key]
        public Guid Id { get; set; }

        [Required, MaxLength(1000)]
        public string Message { get; set; }

        [Required]
        public DateTime Created { get; set; }

        //need to set this up
        public ICollection<Comment> ChildComments { get; set; }

        [Required]
        public Guid PostId { get; set; }

        [Required]
        public Post CommentForPost { get; set; }

        [Required]
        public Guid UserId { get; set; }

        [Required]
        public User CreatedBy { get; set; }
    }

What is the correct way of setting up this relationship while maintaining the one-to-many relationships I have with other entities?? Do I end up creating a join table? I'm not quite sure how I should be setting up my EF relationship to achieve above scenario.

1
0
2/9/2019 6:03:41 AM

Accepted Answer

each Comment should be able to contain a collection of Comment

public class Comment
{
 [Key]
        public Guid Id { get; set; }

        [Required, MaxLength(1000)]
        public string Message { get; set; }

        [Required]
        public DateTime Created { get; set; }

        //need to set this up
        public ICollection<Comment> ChildComments { get; set; }

        [Required]
        public Guid PostId { get; set; }

        [Required]
        public Post CommentForPost { get; set; }

        [Required]
        public Guid UserId { get; set; }

        [Required]
        public User CreatedBy { get; set; }

   //this comment can be a child comment for (if is set) 
   // ParentCommentId is optional
           public string ParentCommentId {get;set;}
           public Comment ParentComment {get;set;}    
   //this comment can have many comments
           public ICollection<Comment> ChildComments {get;set;}

}

then for config. you can do:

 builder.Entity<Comment>()
            .HasOne(x => x.ParentComment)
            .WithMany(x => x.ChildComments)
            .HasForeignKey(x => x.ParentCommentId);
1
2/9/2019 6:39:05 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow