Last active
February 26, 2024 22:15
-
-
Save robsonfaxas/84d831972a6f779ec50ec1c1fe2ff79a to your computer and use it in GitHub Desktop.
[ASP.NET Core TW - EF Core case insensitive SnakeCase] tornar tabelas geradas pelo EF Core NamesToSnakeCase #DotNetCore
This file contains hidden or 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
// 2 classes de métodos de extensão: StringExtensions e ModelBuilderExtensions | |
// 1 - String Extensions | |
using System.Text.RegularExpressions; | |
using Microsoft.EntityFrameworkCore; | |
namespace HelloWorldAspNetCore.Extensions | |
{ | |
public static class StringExtensions | |
{ | |
public 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(); | |
} | |
} | |
} | |
// 2 - ModelBuilderExtensions | |
using Microsoft.EntityFrameworkCore; | |
namespace HelloWorldAspNetCore.Extensions{ | |
public static class ModelBuilderExtensions | |
{ | |
public static void NamesToSnakeCase(this ModelBuilder modelBuilder) | |
{ | |
foreach (var entity in modelBuilder.Model.GetEntityTypes()) | |
{ | |
// Replace table names | |
entity.SetTableName(entity.GetTableName().ToSnakeCase()); | |
// Replace column names | |
foreach (var property in entity.GetProperties()) | |
{ | |
property.SetColumnName(property.GetColumnName().ToSnakeCase()); | |
} | |
foreach (var key in entity.GetKeys()) | |
{ | |
key.SetName(key.GetName().ToSnakeCase()); | |
} | |
foreach (var key in entity.GetForeignKeys()) | |
{ | |
key.SetConstraintName(key.GetConstraintName().ToSnakeCase()); | |
} | |
foreach (var index in entity.GetIndexes()) | |
{ | |
index.SetName(index.GetName().ToSnakeCase()); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment