How do I singularize my tables in EF Code First?

Entity FrameworkEf Code-First

Entity Framework Problem Overview


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

Entity Framework Solutions


Solution 1 - Entity Framework

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

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

Solution 2 - Entity Framework

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.

Solution 3 - Entity Framework

The location of the definition of PluralizingTableNameConvention has moved to:

> using System.Data.Entity.ModelConfiguration.Conventions; >

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontrevorcView Question on Stackoverflow
Solution 1 - Entity FrameworkMorteza ManaviView Answer on Stackoverflow
Solution 2 - Entity FrameworkFranciscoView Answer on Stackoverflow
Solution 3 - Entity FrameworkMythlandiaView Answer on Stackoverflow