Help123
Help123

Reputation: 1453

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

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.

Upvotes: 0

Views: 165

Answers (1)

Lucian Bumb
Lucian Bumb

Reputation: 2881

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);

Upvotes: 1

Related Questions