'Entity Framework Core 5 - Error with recursive structure
I'm trying to setup an entity framework class which has 4 fields that link back to others of the same type or are null. My class looks like this:
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; }
}
This works fine if I only have NorthPatch and SouthPatch but as soon as I add the third one, EastPatch, I get the following error while trying to do the migration:
System.InvalidOperationException: Unable to determine the relationship represented by navigation 'Patch.NorthPatch' of type 'Patch'.
Solution 1:[1]
@Lucutah answers the question as I wrote it but I wanted to post this other solution I found thats worth a look. It has similar results but will also automatically maintain the relationship between East/West and North/South entries. Though this may be no where near as performant depending on what you're trying to do.
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; }
}
In Context..
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");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nathan |
