![](/img/trans.png)
[英]Entity Framework Code First table naming issue, singular confilcts with Plural
[英]In code first “ies” (plural) is mandatory
在這里我試圖使用代碼優先從數據庫獲取數據,但如果我有像Country
一樣的表格,像這樣:
public class Country
{
public int id { get; set; }
public string Name { get; set; }
}
contextdb
public class ContextDb: DbContext
{
public ContextDb() { }
public DbSet<Country> Country { get; set; }
...
}
當我實現了一個Countrys
其拋出一個錯誤:
沒有dbo的
Countries
請嘗試明確指出此特定類型的特定表
public class ContextDb : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Country>().ToTable("Country");
}
public ContextDb() { }
public DbSet<Country> Country { get; set; }
}
作為替代方案,您可以關閉復數約定
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
另一個選擇,如Stefan的回答中所提到的,是對你的模型類有一個屬性(這使得該類“不再是那個POCO-”但在技術上是完全有效的)。
通常我們在DbContext中使用復數形式,如下所示:
public DbSet<Country> Countries { get; set; }
EF使用auto plural
約定,因此您的實體
public class Country
將轉換為數據庫中的數據表[dbo].[Countries]
。
如果要顯式覆蓋數據庫中表的名稱,可以使用以下屬性。
[Table("YourNameHere")]
public class Country
{
public int id { get; set; }
public string Name { get; set; }
}
我認為代碼中的某個地方存在混淆。
另外,如果您願意,也可以將表格放在不同的schema
:
[Table("YourNameHere", Schema = "YourSchemaNameHere")]
public class Country
{
public int id { get; set; }
public string Name { get; set; }
}
請注意重命名模式,我經歷過一些遷移會中斷,因為數據庫索引名稱並不總是正確處理。
注意
請參閱@Wiktor Zychla的解決方案,以禁用整個上下文中的復數約定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.