EF与自定义外键列名

时间:2016-05-20 03:30:24

标签: entity-framework-6

如何使外键列具有自定义名称。默认情况下,EF会将“_”附加到外键列

客户

POCO:

public class Customer 
{
     public int Id { get; set; }
     public string Name { get; set; }
     public virtual Order Order { get; set; }
}

EF配置:

HasKey(m => m.Id);
HasOptional(m => m.Order).WithOptionalPrincipal(e => e.Customer);

客户表:


+====+=======+
| Id | Name  |
+====+=======+
| 1  | Cust1 |
+----+-------+
| 2  | Cust2 |
+----+-------+
| 3  | Cust3 |
+----+-------+
| 4  | Cust4 |
+----+-------+
| 5  | Cust5 |
+====+=======+

顺序

POCO:

public class Order
{
     public int Id { get; set; }
     public string ItemName { get; set; }
     public virtual Customer Customer { get; set; }
}

EF配置:

HasKey(m => m.Id);

订单表:


+====+=============+==========+
| Id | Customer_Id | ItemName |
+====+=============+==========+
| 1  | 2           | Modem    |
+----+-------------+----------+
| 2  | 5           | Router   |
+====+=============+==========+

我如何制作Order表如下(将“CustomerId”作为实际的属性名称)?


+====+=============+==========+
| Id | CustomerId | ItemName |
+====+=============+==========+
| 1  | 2           | Modem    |
+----+-------------+----------+
| 2  | 5           | Router   |
+====+=============+==========+

1 个答案:

答案 0 :(得分:0)

我通常使用属性来直接在实体上定义我的SQL映射(但我可以看到很多理由为什么不这样做)。无论如何,这是使用属性的方法:

public class Order
{
    [Key]
    public int Id { get; set; }

    [Column]
    public string ItemName { get; set; }

    [Column]
    public int? CustomerId { get; set; }

    [ForeignKey("CustomerId")]
    public virtual Customer Customer { get; set; }
}

更新

这样的东西
HasKey(m => m.Id);
HasOptional(m => m.Order)
    .WithOptionalPrincipal(e => e.Customer)
    .Map(m => m.MapKey("CustomerId"));
如果您不想使用属性,

可能会这样做。