使用实体框架7代码优先定义自引用外键关系

Ham*_*lla 3 entity-framework-core ef-fluent-api

我有一个ArticleComment实体,如下所示:

public class ArticleComment
 {
    public int ArticleCommentId { get; set; }
    public int? ArticleCommentParentId { get; set; }

    //[ForeignKey("ArticleCommentParentId")]
    public virtual ArticleComment Comment { get; set; }
    public DateTime ArticleDateCreated  { get; set; }
    public string ArticleCommentName { get; set; }
    public string ArticleCommentEmail { get; set; }
    public string ArticleCommentWebSite { get; set; }
    public string AricleCommentBody { get; set; }

    //[ForeignKey("UserIDfk")]   
    public virtual ApplicationUser ApplicationUser { get; set; }
    public Guid? UserIDfk { get; set; }

    public int ArticleIDfk { get; set; }
    //[ForeignKey("ArticleIDfk")]   
    public virtual Article Article { get; set; }


}
Run Code Online (Sandbox Code Playgroud)

我想以这样的方式定义外键关系,即一个注释可以有很多回复或子,我试图使用流畅的API创建关系,如下所示:

builder.Entity<ArticleComment>()
            .HasOne(p => p.Comment)
            .WithMany()
            .HasForeignKey(p => p.ArticleCommentParentId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired(false);
Run Code Online (Sandbox Code Playgroud)

我按照这里这里提出的解决方案,但我收到错误消息:

在表'ArticleComment'上引入FOREIGN KEY约束'FK_ArticleComment_ArticleComment_ArticleCommentParentId'可能会导致循环或多个级联路径.指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束.无法创建约束或索引.查看以前的错误.

首先,我通过设置OnDelete(DeleteBehavior.Restrict)这将消失,但问题仍然存在,我也尝试使用数据注释,[ForeignKey("ArticleCommentParentId")]因为你可以看到ArticleComment定义中的注释代码,但它没有用,我会欣赏任何虽然就此而言.

E-B*_*Bat 12

您没有正确建模您的实体.每个评论都需要一回复,这些回复也是ArticleComment类型,每个回复都是指向其父回复的回复(注意添加的ICollection回复属性):

  public class ArticleComment
     {
        public ArticleComment()
        {
            Replies = new HashSet<ArticleComment>();
        }

        public int ArticleCommentId { get; set; }
        public int? ParentArticleCommentId { get; set; }
        public virtual ArticleComment ParentArticleComment{ get; set; }
        public virtual ICollection<ArticleComment> Replies { get; set; }

        //The rest of the properties omitted for clarity...
    }
Run Code Online (Sandbox Code Playgroud)

...和流畅的映射:

modelBuilder.Entity<ArticleComment>(entity =>
{
    entity
        .HasMany(e => e.Replies )
        .WithOne(e => e.ParentArticleComment) //Each comment from Replies points back to its parent
        .HasForeignKey(e => e.ParentArticleCommentId );
});
Run Code Online (Sandbox Code Playgroud)

通过上面的设置,您将获得一个开放式树结构.

编辑:使用属性,您只需要装饰ParentArticleComment属性.考虑到在这种情况下EF将按惯例解决所有关系.

[ForeignKey("ParentArticleCommentId")]
public virtual ArticleComment ParentArticleComment{ get; set; } 
Run Code Online (Sandbox Code Playgroud)

对于集合属性,EF非常聪明,可以理解这种关系.