Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
918 views
in Technique[技术] by (71.8m points)

c# - Using Singular Table Names with EF Core 2

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/entity-types?tabs=fluent-api#table-name
        modelBuilder.Entity(entityType.ClrType).ToTable(entityType.ClrType.Name);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...