EF Core relation two primary keys with one foreign key column

122 Views Asked by At
public class PurchaseInvoice
{

    public int Id { get; set; }
    public Int64 InvoiceNumber { get; set; }

    public ICollection<ProductSerial> ProductSerials { get; set; }

}

public class SellingInvoice
{

    public int Id { get; set; }
    public Int64 InvoiceNumber { get; set; }

    public ICollection<ProductSerial> ProductSerials { get; set; }

}

public class ProductSerial
{
    public int Id { get; set; }
    public int Serial_Id { get; set; }
    public int Product_Id { get; set; }
    public int Invoice_Id { get; set; }
    public Enums.InvoiceType InvoiceType { get; set; }

    public PurchaseInvoice? PurchaseInvoice { get; set; }
    public SellingInvoice? SellingInvoice { get; set; }
}

public purchaseInvoiceConfig(EntityTypeBuilder<PurchaseInvoice> entity)
{
    entity.HasMany(q => q.ProductSerials)
          .WithOne(q => q.PurchaseInvoice)
          .IsRequired(false)
          .HasForeignKey(q =>  q.Invoice_Id)
          .OnDelete(DeleteBehavior.NoAction);
}
           
public SellingInvoiceConfig(EntityTypeBuilder<SellingInvoice> entity)
{
    entity.HasMany(q => q.FProductSerials)
          .WithOne(q => q.SellingInvoice)
          .IsRequired(false)
          .HasForeignKey(q => q.Invoice_Id)
          .OnDelete(DeleteBehavior.NoAction);
}

I want use one column foreign key and one type instead of two column nullable, but after inserting data into purchaseInvoice, I get an error about a conflict occurred in database because primary key does not exist in table SellingInvoice.

What's the solution ?

If I remove the physical relationship, the problem will be solved, but I want to use the navigation option to get the ID when inserting.

0

There are 0 best solutions below