Many-to-many relationship in Entity Framework Core when one entity has composite primary key

.net-core c# entity-framework entity-framework-core

Accepted Answer

Comparable to adding a single column of FK is adding composite FK.

The PK column(s) of the referenced object should be added first:

public class InvoiceLineProductCode
{
    public Guid InvoiceLineId { get; set; }
    public InvoiceLine InvoiceLine { get; set; }
    public string ProductCodeCategory { get; set; } // <--
    public string ProductCodeValue { get; set; } // <--
    public ProductCode ProductCode { get; set; }
}

The composite join entity PK is then defined as usual:

modelBuilder.Entity<InvoiceLineProductCode>()
    .HasKey(e => new { e.InvoiceLineId, e.ProductCodeCategory, e.ProductCodeValue });

Additionally, remember to replace theInvoice navigation collection property type:

public class InvoiceLine
{
    public Guid Id { get; set; }
    public int LineNumber { get; set; }    
    public List<InvoiceLineProductCode> ProductCodes { get; set; } // <--
}

and you're done since the names follow EF Core standards. Whenever they fail to do so, the relationship's whole structure is revealed.ProductCode -> InvoiceLineProductCode would be as follows:

modelBuilder.Entity<InvoiceLineProductCode>()
    .HasOne(e => e.ProductCode)
    .WithMany()
    .HasForeignKey(e => new { e.ProductCodeCategory, e.ProductCodeValue })
    .IsRequired()
    .OnDelete(DeleteBehavior.Cascade);
3
2/12/2018 8:27:50 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow