Entity Framework table naming convention

I am using EF 6, I have two simple POCO classes, as shown below:

public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class Company { public int CompanyId { get; set; } public string Name { get; set; } } 

and my context

 public class Context : DbContext { public Context() : base("name=codefirst") { } public DbSet<Person> People { get; set; } public DbSet<Company> Corporation { get; set; } } 

And EF generated tables: dbo.Companies and dbo.People

My question is: why one table name is people and another table name is companies (I know why this is pluralized). I mean, in one table the property name is used, and in the other table is the class name used?

Thanks in advance!

enter image description here

+5
source share
2 answers

Both are displayed using the class name .
The one that probably confused you is the mapping of the Person class. This is one of the rules for pluralizing EF, since people are a plural form of a person (which means more than one person), EF displays it as People. On the other hand, he simply compared the class of the Company with the companies.

You can disable the EF pluralization convention by adding this code to the OnModelCreating() method if you don't like it:

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

+4
source

The Entity Framework (EF) model constructor always refers to your class names when creating tables in the database in the first code approach. In your case, this is Person and Company . EF never refers to properties in your context when creating database tables.

When creating the table, he tries to pluralize the names, so Person got the plural before People and Company got the plural before Companies .

As a quick test, if you change the name of your Company class to Corporation , then the table name will be created as Corporations . I also changed the corresponding Corporation property name in the class context to FooBar

Here is what I did to check this out:

 public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class Corporation { public int CorporationId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class Context : DbContext { public Context() : base("name=codefirst") { } public DbSet<Person> People { get; set; } public DbSet<Corporation> FooBar { get; set; } } 

EF now goes ahead and instead creates the Corporations table ( Corporations plural) and completely ignores the name of the FooBar property that is present in the context class.

It was just a coincidence in your code that you called a property in your context a class like People , which has the plural Person . It embarrassed you and made you think.

+1
source

Source: https://habr.com/ru/post/1261856/


All Articles