如何在 EF Code First 中将我的表单一化? [英] How do I singularize my tables in EF Code First?

查看:24
本文介绍了如何在 EF Code First 中将我的表单一化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在命名我的数据库表时,我更喜欢使用单数名词.然而,首先在 EF 代码中,生成的表总是复数.我的 DbSet 是复数的,我相信这是 EF 生成名称的地方,但我不想将这些名称单数化,因为我相信在代码中让它们复数更实用.我也尝试覆盖设置但无济于事.

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

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>();
     }
}

推荐答案

您为此删除了错误的约定 (PluralizingEntitySetNameConvention).只需将您的 OnModelCreating 方法替换为以下内容即可.

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.

using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db;
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{    
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

使用 Entity Framework 6,在从 DbContext 继承的文件上:

With Entity Framework 6, on your file that inherit from DbContext:

using System.Data.Entity.ModelConfiguration.Conventions;

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

这篇关于如何在 EF Code First 中将我的表单一化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆