问题
I want my domain class name to match my db table name (no pluralisation).
In EF Core 1.1, I used this code to do that:
public static void RemovePluralisingTableNameConvention(this ModelBuilder modelBuilder)
{
foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
{
entityType.Relational().TableName = entityType.DisplayName();
}
}
In EF Core 2.0, this code doesn't compile as Relational()
is not a method on IMutableEntityType.
Anyway, in EF Core 2.0, they have added IPluralizer, documented here:
https://github.com/aspnet/EntityFramework.Docs/blob/master/entity-framework/core/what-is-new/index.md#pluralization-hook-for-dbcontext-scaffolding
There aren't many examples to show how to achieve the same behaviour that I had before. Any clue of how to remove pluralisation in EF Core 2?
回答1:
You can use exactly the same code. Relational()
is extension method defined in the RelationalMetadataExtensions class inside Microsoft.EntityFrameworkCore.Relational.dll
assembly, so make sure you are referencing it.
What about IPluralizer
, as you can see from the link it's just a Pluralization hook for DbContext Scaffolding, i.e. entity class generation from database, used to singularize entity type names and pluralize DbSet names. It's not used for table name generation. The default table name convention is explained in Table Mapping section of the documentation:
By convention, each entity will be setup to map to a table with the same name as the
DbSet<TEntity>
property that exposes the entity on the derived context. If noDbSet<TEntity>
is included for the given entity, the class name is used.
回答2:
You can do it this way without using internal EF API calls by using the ClrType.Name
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
// Use the entity name instead of the Context.DbSet<T> name
// refs https://docs.microsoft.com/en-us/ef/core/modeling/relational/tables#conventions
modelBuilder.Entity(entityType.ClrType).ToTable(entityType.ClrType.Name);
}
}
回答3:
In EF Core 2 you can add a hook. What is mind bending is that if you use this to generate classes in a library project that has the entities for an asp.net core app, you need to go to package manager console select your library project as default project and add those hooks in the mvc web project. If you add the hooks in the library one it doesn't discover the hook.
You can test it works with
public void ConfigureDesignTimeServices(IServiceCollection services)
{
throw new Exception("works");
services.AddSingleton<IPluralizer, MyPluralizer>();
}
来源:https://stackoverflow.com/questions/46497733/using-singular-table-names-with-ef-core-2