Search code examples
c#asp.net-mvcentity-frameworkplural

.NET EF 6 Pluralization with prefix in table names


Plural table names are default convention in EF. but when I have added the prefix I can not make names anymore plural unfortunately. Any ideas?

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
  modelBuilder.Types()
              .Configure(entity => entity.ToTable("MyPrefix_" + entity.ClrType.Name));

  modelBuilder.Conventions.Add<PluralizingTableNameConvention>();
  base.OnModelCreating(modelBuilder);
}

Solution

  • The PluralizingTableNameConvention uses a PluralizationService that can be used anywhere. So you can go ahead and use it in your configuration code.

    Here is an example using a Model "Person" which should be pluralized to "People":

        public DbSet<Person> Persons { get; set; }
    
        protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            var serv = PluralizationService.CreateService(new System.Globalization.CultureInfo("en-us"));
    
            modelBuilder.Types()
             .Configure(entity => entity.ToTable("MyPrefix_" + serv.Pluralize(entity.ClrType.Name)));
    
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    
            base.OnModelCreating(modelBuilder);
        }
    

    After running this code it will correctly pluralize the Persons model to "MyPrefix_People" in the database.

    To you use the PluralizationService you will have to reference the System.Data.Entity.Design assembly.