首先使用实体​​框架7定义自引用外键关系 [英] Defining Self Referencing Foreign-Key-Relationship Using Entity Framework 7 Code First

查看:100
本文介绍了首先使用实体​​框架7定义自引用外键关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an ArticleComment entity as you can see below:

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


}

我想以这样一种方式定义一个外键关系,即一个评论可以有很多回复或孩子,我试图使用这样的流畅API创建这种关系:

I want to define a foreign key relationship in such a way that one comment can have many reply or child, I've tried to create the relationship using fluent API like this:

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

我遵循了建议的解决方案此处,但我得到了消息错误:

I followed the solution that was proposed here and here, but I get an error with the message:

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

Introducing FOREIGN KEY constraint 'FK_ArticleComment_ArticleComment_ArticleCommentParentId' on table 'ArticleComment' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.

首先我虽然通过设置 OnDelete(DeleteBehavior.Restrict)可以解决,但问题仍然存在,我也尝试使用数据注释 [ForeignKey("ArticleCommentParentId)] ,您可以在 ArticleComment 定义中看到注释的代码,但是它没有用,对此我还是表示感谢.

First I though by setting the OnDelete(DeleteBehavior.Restrict) this would go away, but the problem persist, also I've tried to use the data annotation [ForeignKey("ArticleCommentParentId")] as you can see the commented code in the ArticleComment definition, but it didn't work, I'd appreciate any though on this.

推荐答案

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

You are not modeling correctly your entity. Each comment needs a Set of replies, which are of type ArticleComment too, and each of those replies are the ones that point back to its parent (Note the added ICollection Replies property):

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

...以及流利的Mapping:

...and the fluent Mapping:

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

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

With the above setup you get an open-ended tree structure.

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

Using attributes you just need to decorate ParentArticleComment property. Take into account that in this case EF will resolve all the relations by convention.

[ForeignKey("ParentArticleCommentId")]
public virtual ArticleComment ParentArticleComment{ get; set; } 

对于集合属性,EF足够智能,可以理解这种关系.

For collection properties EF is intelligent enough to understand the relation.

这篇关于首先使用实体​​框架7定义自引用外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆