Skip to content

Instantly share code, notes, and snippets.

@uhaciogullari
Created November 15, 2017 23:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uhaciogullari/94bd1e56bbd6feaadfe83b4a61e3e1fd to your computer and use it in GitHub Desktop.
Save uhaciogullari/94bd1e56bbd6feaadfe83b4a61e3e1fd to your computer and use it in GitHub Desktop.
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