Different database objects follow different naming conventions. To accommodate different databases, EF Core provides several naming convention configuration options.
Common Naming Styles
| Naming policy | Original | Converted |
|---|---|---|
| PascalCase | HelloShop | HelloShop |
| CamelCase | HelloShop | helloShop |
| SnakeCaseLower | HelloShop | hello_shop |
| SnakeCaseUpper | HelloShop | HELLO_SHOP |
| KebabCaseLower | HelloShop | hello-shop |
| KebabCaseUpper | HelloShop | HELLO-SHOP |
You can use the Humanizr library to convert strings between different naming styles.
Singular or Plural Table Names
By default, EF Core uses the singular form for table names. You can use a convention-based configurator or manually specify plural table names. The community debate over singular versus plural table names has always existed and there is no unified standard, but Zero recommends the singular form.
Manually Specifying Table and Column Names
Table Names
By default, EF Core uses the entity type name as the table name. You can change the table name by overriding the OnModelCreating method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().ToTable("blogs");
}
Column Names
By default, EF Core uses property names as column names. You can change a column name with the HasColumnName method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().Property(b => b.Url).HasColumnName("blog_url");
}
PostgreSQL Naming Conventions
PostgreSQL naming conventions use lowercase snake_case — words separated by underscores, such as blog_url — with singular table names.
Using the EFCore.NamingConventions Library
The EFCore.NamingConventions library provides naming convention configuration options that make it easy to configure table names, column names, and so on.
Installing the EFCore.NamingConventions Library
dotnet add package EFCore.NamingConventions
Configuring the Naming Convention
Configure the naming convention using the OnConfiguring method:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSnakeCaseNamingConvention();
}
Or configure it in the dependency injection container:
builder.Services.AddDbContext<MyDbContext>(options => options.UseNpgsql().UseSnakeCaseNamingConvention());
Changing the Migrations History Table Name
By default, EF Core keeps track of which migrations have been applied to the database by recording them in a table named __EFMigrationsHistory. For various reasons, you may want to customize this table to better suit your needs.
options.UseSqlServer(connectionString,x => x.MigrationsHistoryTable("__MyMigrationsHistory", "mySchema"));
https://learn.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/history-table