我正在尝试设置一个实体框架类,该类有4个字段,这些字段链接到相同类型的其他字段或为null。我的课是这样的:
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'.
发布于 2021-01-23 23:51:26
那是个很酷的虫子!我能够复制,并作为一个额外的发现,错误报告,仍然开放的EF核心。
Open: https://github.com/dotnet/efcore/issues/21968
类似问题: Entity Framework Core One-One Self Referencing Relationship fails
解决方案:移除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");
发布于 2021-01-24 00:46:31
@Lucutah在我写的时候回答了这个问题,但是我想发布另一个我认为值得一看的解决方案。它有类似的结果,但也将自动保持东西和南北条目之间的关系。不过,根据你想要做的事情,这不太像表演家。
public class Patch : EntityBase
{
public int PatchId { get; set; }
public virtual Patch NorthPatch { get; set; }
public virtual Patch SouthPatch { get; set; }
public virtual Patch EastPatch { get; set; }
public virtual Patch WestPatch { get; set; }
}
在上下文中。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Patch>().HasKey("PatchId");
modelBuilder.Entity<Patch>()
.HasOne(x => x.NorthPatch)
.WithOne(x => x.SouthPatch)
.HasForeignKey(typeof(Patch), "NorthPatchId");
modelBuilder.Entity<Patch>()
.HasOne(x => x.EastPatch)
.WithOne(x => x.WestPatch)
.HasForeignKey(typeof(Patch), "EastPatchId");
}
https://stackoverflow.com/questions/65864962
复制相似问题