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

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

问题描述

我更喜欢在命名我的数据库表时使用单数名词。然而,在EF代码中,生成的表始终是复数形式。我的DbSets是多元化的,我相信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天全站免登陆