Search code examples
ef-code-firstfluent-interface

Define association using database column and not entity type property


public class Order {
   public int OrderID {get; set;}
   public DateTime DateOrdered { get; set; }
   public ICollection<OrderLine> OrderLines { get; set; }
}

public class OrderLine{
    public int OrderLineID { get; set; }
    public int OrderID {get; set; } // I want to remove this
    public string ItemName { get; set;}
    public Int Qty { get; set; }
}

How would I map these using the Fluent API? I am using these in a repository pattern where Order will be the root of the aggregate. As such I do not want OrderLine to have a reference to Order or have an OrderID. Since the OrderLine only makes any sense because its a child of Order.

Currently I am using this:

HasMany<OrderLine>(x => x.OrderLines).WithRequired().HasForeignKey(x => x.OrderID);

I am using an existing database structure here and ideally I would map this using the database column name. So somehow tell it to use tblOrderLine.colOrderId rather then OrderLine.OrderID.


Solution

  • You can use the Map() method to map your FK

    HasMany<OrderLine>(x => x.OrderLines)
    .WithRequired()
    .Map(m => m.MapKey("colOrderId"));