I have a self-referencing entity in my app. A package type with dependencies (as a list) to other package types. I am trying to design the required intermediate table with the model builder. Unfortunately I can't manage to fill the key correctly.
System.InvalidOperationException: 'Unable to track an entity of type 'PackageDependency (Dictionary<string, object>)' because its primary key property 'DependencyId' is null.'
public class PackageType
{
[Key]
public String Tag { get; set; }
public virtual List<PackageType> Dependencies { get; set; } = new List<PackageType>();
}
DB Context:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PackageType>()
.HasMany(p => p.Dependencies)
.WithMany(p => p.Dependencies)
.UsingEntity<Dictionary<string, object>>(
"PackageDependency",
j => j
.HasOne<PackageType>()
.WithMany()
.HasForeignKey("PackageId")
.HasConstraintName("FK_PackageDependency_PackageId")
.OnDelete(DeleteBehavior.Cascade),
j => j
.HasOne<PackageType>()
.WithMany()
.HasForeignKey("DependencyId")
.HasConstraintName("FK_PackageDependency_DependencyId")
.OnDelete(DeleteBehavior.ClientCascade),
e => e.HasKey("PackageId", "DependencyId"));
}
Does anyone have a hint for me?
Thanks a lot!
question from:https://stackoverflow.com/questions/65944269/self-referencing-table-with-entity-framework-core-5