Created
November 15, 2017 23:43
-
-
Save uhaciogullari/94bd1e56bbd6feaadfe83b4a61e3e1fd to your computer and use it in GitHub Desktop.
Use Postgres naming conventions in EF Core
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
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