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
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
OrderItemclass in two different databases: in database A everyOrderItemhas a foreign key to theOrderthat it belongs to namedOrderId, in database B you want a foreign key namedorder_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
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.