首页 > 解决方案 > Entity Framework Core 5 - 递归结构错误

问题描述

我正在尝试设置一个实体框架类,它有 4 个字段链接回相同类型的其他字段或为空。我的课看起来像这样:

public class Patch : EntityBase
{
    [Key]
    public int PatchId { get; set; }

    [ForeignKey("NorthPatchId")]
    public virtual Patch NorthPatch { get; set; }

    [ForeignKey("SouthPatchId")]
    public virtual Patch SouthPatch { get; set; }

    [ForeignKey("EastPatchId")]
    public virtual Patch EastPatch { get; set; }

    [ForeignKey("WestPatchId")]
    public virtual Patch WestPatch { get; set; }
}

如果我只有 NorthPatch 和 SouthPatch,这可以正常工作,但是一旦我添加第三个 EastPatch,我在尝试进行迁移时收到以下错误:

System.InvalidOperationException: Unable to determine the relationship represented by navigation 'Patch.NorthPatch' of type 'Patch'.

标签: entity-framework-coreef-core-5.0

解决方案


这是一个非常酷的错误!我能够复制,并且作为奖励发现了报告的错误并且仍然对 EF Core 开放。

打开错误: https ://github.com/dotnet/efcore/issues/21968

类似问题: Entity Framework Core 一对一自引用关系失败

解决方法: 删除 [ForeignKey] 属性,并将以下内容用于您的 OnModelConfiguring 作为您的上下文。

builder.Entity<Patch>()
    .HasOne(x => x.NorthPatch)
    .WithOne()
    .HasForeignKey(typeof(Patch), "NorthPatchId");

builder.Entity<Patch>()
    .HasOne(x => x.SouthPatch)
    .WithOne()
    .HasForeignKey(typeof(Patch), "SouthPatchId");

builder.Entity<Patch>()
    .HasOne(x => x.EastPatch)
    .WithOne()
    .HasForeignKey(typeof(Patch), "EastPatchId");

builder.Entity<Patch>()
    .HasOne(x => x.WestPatch)
    .WithOne()
    .HasForeignKey(typeof(Patch), "WestPatchId");

推荐阅读