In order to set singular table names in EF Core 5 you can do the following
modelBuilder.Model.GetEntityTypes()
.Configure(et => et.SetTableName(et.DisplayName()));
but then if you have value objects in you domain they will all be treated as entity types and created as tables in the database. If your value objects all inherit from a base type like ValueObject
you can use the following:
modelBuilder.Model.GetEntityTypes()
.Where(x => !x.ClrType.IsSubclassOf(typeof(ValueObject)))
.Configure(et => et.SetTableName(et.DisplayName()));
Another drawback in EF Core 5 is that when you use inheritance in your entity model, setting tables names changes from Table-per-Hierarchy (TPH) to Table-per-Type (TPT)
You could use the following alternative (assuming your entities derive from BaseEntity
)
modelBuilder.Model.GetEntityTypes()
.Where(x => x.ClrType.BaseType == typeof(BaseEntity))
.Configure(et => et.SetTableName(et.DisplayName()));
where Configure is defined as an extension method:
public static class ModelBuilderExtensions
{
public static IEnumerable<IMutableEntityType> EntityTypes(this ModelBuilder builder)
{
return builder.Model.GetEntityTypes();
}
public static IEnumerable<IMutableProperty> Properties(this ModelBuilder builder)
{
return builder.EntityTypes().SelectMany(entityType => entityType.GetProperties());
}
public static IEnumerable<IMutableProperty> Properties<T>(this ModelBuilder builder)
{
return builder.EntityTypes().SelectMany(entityType => entityType.GetProperties().Where(x => x.ClrType == typeof(T)));
}
public static void Configure(this IEnumerable<IMutableEntityType> entityTypes, Action<IMutableEntityType> convention)
{
foreach (var entityType in entityTypes)
{
convention(entityType);
}
}
public static void Configure(this IEnumerable<IMutableProperty> propertyTypes, Action<IMutableProperty> convention)
{
foreach (var propertyType in propertyTypes)
{
convention(propertyType);
}
}
}