The default naming conventions for Entity Framework Core are quite annoying when using PostgreSQL. EF Core generates all databases objects using Pascal Casing, as a consequence you have to add quotes to all queries which exactly ain’t fun if you have to write some queries by hand.
Let’s update the naming convention to use snake_case which is what PostgreSQL expects.
Let’s start by adding a simple ToSnakeCase extension method:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class StringExtensions | |
{ | |
public static string ToSnakeCase(this string input) | |
{ | |
var startUnderscores = Regex.Match(input, @"^_+"); | |
return startUnderscores + Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower(); | |
} | |
} |
Now it’s time to update our OnModelCreating method and change the naming convention:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SampleDbContext : DbContext | |
{ | |
public SampleDbContext(DbContextOptions options) | |
: base(options) | |
{ } | |
protected override void OnModelCreating(ModelBuilder builder) | |
{ | |
base.OnModelCreating(builder); | |
foreach(var entity in builder.Model.GetEntityTypes()) | |
{ | |
// Replace table names | |
entity.Relational().TableName = entity.Relational().TableName.ToSnakeCase(); | |
// Replace column names | |
foreach(var property in entity.GetProperties()) | |
{ | |
property.Relational().ColumnName = property.Relational().ColumnName.ToSnakeCase(); | |
} | |
foreach(var key in entity.GetKeys()) | |
{ | |
key.Relational().Name = key.Relational().Name.ToSnakeCase(); | |
} | |
foreach(var key in entity.GetForeignKeys()) | |
{ | |
key.Relational().Name = key.Relational().Name.ToSnakeCase(); | |
} | |
foreach(var index in entity.GetIndexes()) | |
{ | |
index.Relational().Name = index.Relational().Name.ToSnakeCase(); | |
} | |
} | |
} | |
} |
That’s it!