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

佐手、 提交于 2019-12-13 04:08:05

问题


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:


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


来源:https://stackoverflow.com/questions/54603697/ef-core-how-to-setup-many-to-many-for-same-entity-that-already-has-a-one-to-ma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!