简体   繁体   中英

Making a foreign key as a subset of a composite primary key in EF

I have a table with composite primary key: { OrderNumber, OrderLine, OrderItem }, with a foreign key on { OrderNumber, OrderLine }. How can I achieve this with code first in Entity Framework?

My attempt:

public class OrderDetails 
{
    [Key, ForeignKey("Order"), Column(Order = 0)]
    public int OrderNumber { get; set; }

    [Key, ForeignKey("Order"), Column(Order = 1)]
    public int OrderLine { get; set; }

    [Key, Column(Order = 2)]
    public int OrderItem { get; set; } 

    // ... Other properties
}

It's easy to do with fluent mapping and navigation properties (actually I prefer fluent mapping, because it allows to keep entities clear without 'polluting' them with data provider specific attributes). Suppose your order class looks like

public class Order
{
    public int Number { get; set; }
    public int Line { get; set; }
    // ...
    public virtual ICollection<OrderDetails> Details { get; set; }
}

Then mapping will look this way

modelBuilder.Entity<Order>()
    .HasKey(o => new { o.Number, o.Line });

modelBuilder.Entity<OrderDetails>()
    .HasKey(od => new { od.OrderNumber, od.OrderLine, od.OrderItem });

modelBuilder.Entity<OrderDetails>()
    .HasRequired(od => od.Order)
    .WithMany(o => o.Details)
    .HasForeignKey(od => new { od.OrderNumber, od.OrderLine });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM