【问题标题】:EF Code first 4.3 naming convention foreign keyEF Code first 4.3 命名约定外键
【发布时间】:2012-04-21 11:26:16
【问题描述】:

我有以下实体:

public class User
{
    public int ID {get; set;}

    public int GroupID {get; set;}     // navigation property with 
    public Group Group {get; set;}     // foreign key field

    public Adress Adress {get; set;}   // navigation property only

}

实体框架生成的表格如下:

ID
GroupID
Adress_ID

我不喜欢 FK 列的列命名不一样。我可以实现两者都使用相同的约定“GroupID,AdressID”或“Group_ID,Adress_ID”吗?

我使用约定优于配置,不想使用 Fluent API。

【问题讨论】:

    标签: .net entity-framework ef-code-first entity-framework-migrations


    【解决方案1】:

    EF 4.1 到 4.3 不支持创建自定义约定,因此不可能。您唯一能做的(没有 Fluent API)可能是将外部属性映射到另一个列名:

    [Column("Group_ID")]
    public int GroupID {get; set;}
    

    然后您在数据库中拥有两个带下划线的 FK 列。但是 - 如您所见 - 您至少需要用数据注释覆盖约定。

    只有使用 Fluent API 才能定义不带下划线的第二个 FK 列:

    modelBuilder.Entity<User>()
        .HasOptional(u => u.Address)
        .WithMany()
        .Map(x => x.MapKey("AddressID"));
    

    【讨论】:

    • http://stackoverflow.com/questions/18050590/why-does-ef5-create-foreign-keys-with-id-but-recommend-naming-convention-id-wi/18066373?noredirect=1#18066373 解释了该列出现的原因
    猜你喜欢
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    相关资源
    最近更新 更多