Error during insert many-to-many relationship in EF Core

41 views Asked by At

I got this error during insert:

The value of 'ContractHeaderSupplier.SupplierId' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known

This is my setup:

[Table("ContractHeader")]
public class ContractHeader
{
    [Key]
    public int Id { get; set; }
    ....
    public virtual List<Supplier> Supplier { get; set; } = new();
}

[Table("Supplier")]
public class Supplier
{
    [Key]
    public int Id { get; set; }
    ...
    public virtual List<ContractHeader> ContractHeader { get; set; } = new();
}

I tried different variations of fluent api setup, here is few one

 modelBuilder.Entity<Supplier>()
   .HasMany(e => e.ContractHeader)
   .WithMany(e => e.Supplier);
 // .UsingEntity<ContractHeaderSupplier>();
 //.UsingEntity("ContractHeaderSupplier");

My relationship table is

CREATE TABLE [dbo].[ContractHeaderSupplier]
(
   [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
   [ContractHeaderId] [int] NOT NULL FOREIGN KEY([ContractHeaderId]) REFERENCES [dbo]. 
   [ContractHeader] ([Id]),
   [SupplierId] [int] NOT NULL 
        FOREIGN KEY([SupplierId]) REFERENCES [dbo].[Supplier] ([Id])
) 

How to fix this?

Update:

This does not work also:

.UsingEntity("ContractHeaderSupplier",
    l => l.HasOne(typeof(Supplier)).WithMany().HasForeignKey("SupplierId"),
    r => r.HasOne(typeof(ContractHeader)).WithMany().HasForeignKey("ContractHeaderId"));

Update

I have found a fix

CREATE TABLE [dbo].[Supplier](
    [Id] [int] NOT NULL IDENTITY(1,1) PRIMARY KEY,

previous setup was

IDENTITY(0,1)

Anyway, I'll be glad to hear explanation

0

There are 0 answers