Skip to content

Instantly share code, notes, and snippets.

@RobsonFaxas
Last active February 26, 2024 22:15
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 RobsonFaxas/84d831972a6f779ec50ec1c1fe2ff79a to your computer and use it in GitHub Desktop.
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
// 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