Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use Postgres naming conventions in EF Core
static class ModelBuilderExtensions
{
public static void UsePostgresConventions(this ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.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.Name.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();
}
}
}
private static string ToSnakeCase(this string input)
{
if (string.IsNullOrEmpty(input)) { return input; }
var startUnderscores = Regex.Match(input, @"^_+");
return startUnderscores + Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment