entity-framework-core - 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'.
解决方案
这是一个非常酷的错误!我能够复制,并且作为奖励发现了报告的错误并且仍然对 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");
推荐阅读
- c# - 如何从表的html列中获取数据并传递给C#
- reactjs - React Native - 在 maxlength 之后移动到下一个输入
- python - 如何用 allennlp 训练语义角色标签?
- python - 创建一个新数据框,其中某些行是另一个数据框中单行的扩展版本
- android - Android 快捷方式在 VIVO 10 中不起作用
- xamarin - 设置默认页面并添加标签点击事件
- python - 如何从列表中随机打印不带括号、引号和逗号的单词
- python - 如何将每个条形的值显示到 matplotlib 中的条形图中
- database - 使用数据库中的 foreach 时下拉菜单为空
- c++ - 与另一个列表相比,如何过滤 std::list 并删除不匹配的项目?