如何在 EF Code First 中对表进行单一化?
在命名数据库表时,我更喜欢使用单数名词。然而,在 EF 代码优先中,生成的表始终是复数。我的 DbSet 是复数的,我相信这是 EF 生成名称的地方,但我不想将这些名称单数化,因为我相信在代码中使用复数名称更实用。我也尝试过覆盖该设置但无济于事。
有什么想法吗?这是我的代码,谢谢。
MyObjectContext.cs
public class MyObjectContext : DbContext, IDbContext
{
public MyObjectContext(string connString) : base(connString)
{
}
public DbSet<Product> Products {get;set;}
public DbSet<Category> Categories {get;set;}
//etc.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
}
}
I prefer using singular nouns when naming my database tables. In EF code first however, the generated tables always are plural. My DbSets are pluralized which I believe is where EF is generating the names but I don't want to singularize these names as I believe it is more pratical to have them plural in code. I also tried overriding the setting but to no avail.
Any ideas? Here is my code and thanks.
MyObjectContext.cs
public class MyObjectContext : DbContext, IDbContext
{
public MyObjectContext(string connString) : base(connString)
{
}
public DbSet<Product> Products {get;set;}
public DbSet<Category> Categories {get;set;}
//etc.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为此,您已删除了错误的约定 (PluralizingEntitySetNameConvention)。只需将您的 OnModelCreating 方法替换为以下内容即可。
对于 Entity Framework 6,在从 DbContext 继承的文件上:
You've removed the wrong convention (PluralizingEntitySetNameConvention) for this purpose. Just replace your OnModelCreating method with the below and you will be good to go.
With Entity Framework 6, on your file that inherit from DbContext:
您还可以更改属性值:
在“工具”菜单上,单击“选项”。
在“选项”对话框中,展开“数据库工具”。
单击 O/R 设计器。
将名称的复数设置为 Enabled = False 以设置 O/R 设计器,使其不会更改类名称。
将名称复数设置为 Enabled = True,以将复数规则应用于添加到 O/R 设计器的对象的类名称。
You can also change the property value:
On the Tools menu, click Options.
In the Options dialog box, expand Database Tools.
Click O/R Designer.
Set Pluralization of names to Enabled = False to set the O/R Designer so that it does not change class names.
Set Pluralization of names to Enabled = True to apply pluralization rules to the class names of objects added to the O/R Designer.
PluralizingTableNameConvention 的定义位置已移至:
The location of the definition of PluralizingTableNameConvention has moved to: