如果我有以下型号:如何使Entity Framework在命名外键时使用表名而不是类名?
实体框架使用Person
和Address
正确的表名,但在Address
的外键被称作PersonDao_Id
。我希望它是Person_Id
。
这是一个错误还是我应该为属性名称编写自定义约定?
注意:我使用MySQL与实体框架,我不知道这是否重要。
编辑:我知道我可以使用ForeignKey
属性或流利的API手动指定列名。我需要这个自动和全局的工作。
如果我有以下型号:如何使Entity Framework在命名外键时使用表名而不是类名?
实体框架使用Person
和Address
正确的表名,但在Address
的外键被称作PersonDao_Id
。我希望它是Person_Id
。
这是一个错误还是我应该为属性名称编写自定义约定?
注意:我使用MySQL与实体框架,我不知道这是否重要。
编辑:我知道我可以使用ForeignKey
属性或流利的API手动指定列名。我需要这个自动和全局的工作。
使用属性,就像你做对表和类不同的名字:
[Table("Address")]
public class AddressDao
{
public Guid Id { get; set; }
[ForeignKey("Person_Id")]
public PersonDao Person { get; set; }
// other properties
}
如果你不想使用默认的惯例,你可以只从你的类名中Dao
:
public class Person
{
public Guid Id { get; set; }
public ICollection<Address> { get; set; }
// other properties
}
public class Address
{
public Guid Id { get; set; }
public Person Person { get; set; }
// other properties
}
我很抱歉,但我的问题并不清楚enogh。我已经知道这件事。我需要这个自动和全局的工作。 –
所以你可以使用属性来指定一个表名而不是列名?为什么不直接在没有“Dao”的情况下命名你的班级呢?要回答这个问题,我不知道如何全局覆盖默认约定。 –
我喜欢将我的数据访问类命名为Dao,以将它们与我的域类(具有不能使用EF直接映射的结构)区分开来。 –
如果要在数据库中创建自己的专栏名称,可以在数据库上下文中使用Fluent API的protected override void OnModelCreating(DbModelBuilder modelBuilder)
方法。使用列名添加到您的DAO类属性。
[Table("Person")]
public class PersonDao
{
public Guid Id { get; set; }
public ICollection<Address> Addresses { get; set; }
// other properties
}
[Table("Address")]
public class AddressDao
{
public Guid Id { get; set; }
public Guid MyPersonDaoColumnName { get; set; }
public PersonDao Person { get; set; }
// other properties
}
,然后用流利的API写:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AddressDao>().HasRequired(x => x.Person)
.WithMany(x => x.Addresses)
.HasForeignKey(x => x.MyPersonDaoColumnName);
}
,但它是丑陋与属性混合流利的API,所以你也需要:
modelBuilder.Entity<AddressDao>.ToTable("Address");
modelBuilder.Entity<PersonDao>.ToTable("Person");
http://stackoverflow.com/问题/ 11148662/mapping -a-foreign-key-with-a-custom-column-name可能是有用的 – Vladimir
[ForeignKey(“Person_Id”)]和详细信息在这里:http://stackoverflow.com/questions/5082991/influencing -foreign-key-column-naming-in-ef-code-first-ctp5 – Mehmet