简体   繁体   English

EF Core-如何为已经存在一对多关系的同一实体设置多对多

[英]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 . 我目前在PostComment之间有一对多的关系。 One Post can contain multiple Comments . 一个Post可以包含多个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 . 我在UserComment之间也有一对多的关系。

Ie each Comment should be able to contain a collection of Comment . 即每个Comment应该能够包含Comment的集合。 Eg 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. 我不太确定如何建立我的EF关系以实现上述情况。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM