如果我有以下型號:如何使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