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

时间:2018-11-13 14:20:26

标签: c# entity-framework entity-framework-6.2

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 个答案:

答案 0 :(得分:0)

人们倾向于在其实体类中使用属​​性来设计数据库中表和列的名称。但是,这限制了实体类的可重用性。

假设您希望在两个不同的数据库中使用OrderItem类:在数据库A中,每个OrderItem都具有一个属于它的Order的外键,名为OrderId,在数据库B,您需要一个名为order_id的外键。

但是,您是一个优秀的程序员,您的类非常受欢迎,并且您不想通过限制类的使用而使他们失望。因此,您使用fluent API来设计数据库而不是属性。

Fluent API用于覆盖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");
}

由于您遵循entity framework coding conventions来设计一对多,因此您不必在模型构建器中对其进行建模。我只是为了完整性而添加它。