【问题标题】:Self-referencing relationship in EF Core 5EF Core 5 中的自引用关系
【发布时间】:2021-08-13 06:50:26
【问题描述】:

我正在尝试在数据库中创建一个树结构,其中项目可以相互引用。我认为这是一项简单的任务,但是,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 不会生成迁移。

【问题讨论】:

    标签: entity-framework-core ef-code-first


    【解决方案1】:

    忽略这个问题,我已经发现了自己的错误。我会把它留在这里,以防有人遇到同样的问题,因为错误消息非常具有误导性。

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 2021-07-21
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多