How to add foreign key custom name in Entity Framework 6.2?

544 Views Asked by At

How to set custom foreign key name in Entity Framework 6.2 code-first? I have two classes, Order and OrderItem.

public partial class Order
{
    public int Id { get; set; }
    public string orderNumber { get; set; }
    public virtual ICollection<OrderItem> orderItems { get; set; }
}

public partial class OrderItem
{
    public string itemNo { get; set; }

    [Column("order_Id")]
    [ForeignKey("CurrentOrder")]

    public int orderId { get; set; }
    public virtual Order CurrentOrder { get; set; }
}

How to set specific relation name such as 'fk_order_items' using Entity Framework 6.2 code-first? Set order-id in Order-item as foreign key

1

There are 1 best solutions below

0
Harald Coppoolse On

People tend to use attributes in their entity classes to design the names of the tables and columns in the database. However that limits reusability of the entity classes.

Suppose you want your OrderItem class in two different databases: in database A every OrderItem has a foreign key to the Order that it belongs to named OrderId, in database B you want a foreign key named order_id.

Yet you are a good programmer, your classes are very popular, and you don't want to disappoint the users of your classes by limiting their usage. Hence you use fluent API to design the database instead of attributes.

Fluent API is used in your overrid of DbContext.OnModelCreating

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     // in databases for this context, every OrderItem belongs to exactly one Order
     // using foreign key "order_id"

     // model the table with the OrderItems:
     var orderItemTableBuilder = modelBuilder.Entity<OrderItem>();
     // (1) if needed: give it a non-default table name
     // (2) if needed: tell which property is the primary key
     // (3) design the one-to-many:
     //     (3a) between which tables?
     //     (3b) which property holds the foreign key?
     orderItemTableBuilder
         .ToTable("MyTableName")                          // (1)
         .HasKey(orderItem => orderItem.ItemNo            // (2)
         // (3) design one to many
         .HasRequired(orderItem => orderItem.Order)       // (3a) 
         .WithMany(order => order.OrderItems)             // (3a)
         .HasForeignKey(orderItem => orderItem.orderId);  // (3b)

     // model property orderId: it must be stored in column "order_id"
     orderItemTableBuilder.Property(orderItem => orderItem.orderId)
          .HasColumnName("order_id");
}

Because you followed the entity framework coding conventions to design your one-to-many, you won't have to model it in your model builder. I only added it for completeness.