I’ve been playing around with .NET recently to see if I like it as a strongly typed web framework. One issue I ran into
though, was that the naming conventions with Entity Framework leverage pascal case. I appreciate that this closely
matches the code, but I have been using Postgres for my database of choice lately and case-sensitive naming is a pain
in that environment.
I found like-minded individuals discussing options in GitHub issues
and blogs,
and really appreciated the insights. So that I don’t have to count on finding those posts again, below is the DbContext
I put together to convert naming conventions from pascal case to snake case. Along with converting to snake case, I
also removed the asp_net_ prefix from the converted .NET Identity tables. This code is almost entirely copy-pasted from the
other sources, so I’m not trying to take credit for it, really just documenting it for myself.
usingMicrosoft.EntityFrameworkCore;usingSystem.Collections.Generic;namespaceApp.Data{publicclassAppDbContext:DbContext{publicAppDbContext(DbContextOptions<AppDbContext>options):base(options){}protectedoverridevoidOnModelCreating(ModelBuilderbuilder){base.OnModelCreating(builder);// Npgsql comes with a it's own translator, making conversion easy
varmapper=newNpgsql.NameTranslation.NpgsqlSnakeCaseNameTranslator();foreach(varentityinbuilder.Model.GetEntityTypes()){entity.Relational().TableName=mapper.TranslateTypeName(entity.Relational().TableName);foreach(varpropertyinentity.GetProperties()){property.Relational().ColumnName=mapper.TranslateMemberName(property.Name);}foreach(varkeyinentity.GetKeys()){key.Relational().Name=mapper.TranslateMemberName(key.Relational().Name);}foreach(varkeyinentity.GetForeignKeys()){key.Relational().Name=mapper.TranslateMemberName(key.Relational().Name);}foreach(varindexinentity.GetIndexes()){index.Relational().Name=mapper.TranslateMemberName(index.Relational().Name);}// Drop the 'asp_net_' prefix from the Identity tables
if(entity.Relational().TableName.StartsWith("asp_net_")){entity.Relational().TableName=entity.Relational().TableName.Replace("asp_net_",string.Empty);}}}}}