微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

EF Core 5 中的自引用关系

如何解决EF Core 5 中的自引用关系

我正在尝试在 db 中创建一个树结构,其中项目可以相互引用。我认为这是一项简单的任务,但是,EF Core 决定罢工。我无法让它生成正确的外键,它不断抛出异常:

Unable to determine the relationship represented by navigation 'Item.Parent' of type 'Item'. Either manually configure the relationship,or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

我的类看起来像这样(简化):

public class Item
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    [ForeignKey("Parent")]
    public Guid? ParentId { get; set; }

    public virtual Item Parent { get; set; }

    [InverseProperty("Parent")]
    public virtual IEnumerable<Item> Children { get; set; }
}

我什至尝试删除 Children 属性,但结果相同。

我尝试过的另一件事是 Fluent API:

entity
    .HasOne(e => e.Parent)
    .WithMany(e => e.Children)
    .HasForeignKey(e => e.ParentId);

//or 
entity
    .HasOne<Item>(e => e.Parent)
    .WithMany()
    .HasForeignKey(e => e.ParentId);

//or
entity
    .HasMany(e => e.Children)
    .WithOne(e => e.Parent)
    .HasForeignKey(e => e.ParentId);

//or
entity
    .HasMany(e => e.Children)
    .WithOne(e => e.Parent);

它们都不断产生相同的错误我有点不知所措。

我也在看其他一些答案,它们看起来很像我想要做的,但是,我的 EF 不会生成迁移。

解决方法

无视这个问题,我已经找出了我自己的错误。我会留在这里以防有人遇到同样的问题,因为错误信息非常具有误导性。

发生的事情是复制和粘贴问题,我为不相关的实体创建了另一个配置,但忘记更新类型:

    {
        public void Configure(EntityTypeBuilder<Item> entity)
        {
            entity
                .HasNoKey();
        }
    }

注意泛型定义中的 Item 类型。这导致 EF Core 删除了最初在实体上设置的键,并使 EF Core 对这种关系感到困惑(因为现在我将外键定位到既不是键也不是索引的属性)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。