【问题标题】:EF Core - How to setup many-to-many for same entity that already has a one-to-many relationshipEF Core - 如何为已经具有一对多关系的同一实体设置多对多
【发布时间】:2019-02-09 14:39:05
【问题描述】:

我目前在PostComment 之间存在一对多关系。一个Post 可以包含多个Comments。我想做的是为评论创建多对多关系。我在UserComment 之间也有一对多的关系。

即每个Comment 应该能够包含Comment 的集合。例如。一个用户可以评论另一个用户的评论。我想保留 cmets 的顺序,以便以正确的顺序显示它们。

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

在保持我与其他实体的一对多关系的同时建立这种关系的正确方法是什么?我最终会创建一个连接表吗?我不太确定应该如何设置我的 EF 关系以实现上述情况。

【问题讨论】:

    标签: c# entity-framework entity-framework-core


    【解决方案1】:

    每个评论应该能够包含评论的集合

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

    然后进行配置。你可以这样做:

     builder.Entity<Comment>()
                .HasOne(x => x.ParentComment)
                .WithMany(x => x.ChildComments)
                .HasForeignKey(x => x.ParentCommentId);
    

    【讨论】:

    • 当你说父评论是可选的,它的目的是什么?如果我在帖子中插入评论,我将在 parentcommentid 和 parentcomment 为空的情况下插入它。然后,如果有人回复该评论,我会将其插入 ChildComments。这是正确的方法吗?
    • ParentComment 是可选的,表示不强制设置值。并非所有 cmets 都会有子 cmets。当您想要获取评论的所有子 cmets 时使用的 ChildComments。
    • 明白了。所以本质上,parentcommentid 是在我插入子评论时设置的。如果用户回复评论,则将回复设置为子评论,将父评论id设置为他们回复的评论。我的想法正确吗?
    • 当用户回复评论时,您只需将回复的 ParentCommentId 设置为与评论的 Id 相同
    • 嗯,有道理。只需设置外键,以便 EF 处理其余部分。那讲得通。感谢您的帮助和解释
    猜你喜欢
    • 2019-03-06
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2023-03-07
    相关资源
    最近更新 更多