[英]EF Core - How to setup many-to-many for same entity that already has a one-to-many relationship
我目前在Post
和Comment
之间有一对多的关系。 一个Post
可以包含多个Comments
。 我想要做的是为评论创建多对多关系。 我在User
和Comment
之间也有一对多的关系。
即每个Comment
应该能够包含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; }
}
在维持我与其他实体的一对多关系的同时,建立这种关系的正确方法是什么? 我最终会创建联接表吗? 我不太确定如何建立我的EF关系以实现上述情况。
每个评论应能够包含评论的集合
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.