1

I would like to configure ASP.NET Core Identity Framework + EF Core on Postgres with lowercase snake_case table names. As it currently stands my IdentityDbContext looks like this:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace TestProj.Identity;

public class IdentityDbContext : IdentityDbContext<ApplicationUser>
{
    public IdentityDbContext(DbContextOptions options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .LogTo(Console.WriteLine, LogLevel.Information)
            .UseSnakeCaseNamingConvention()
            .EnableSensitiveDataLogging();
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        // correctly set the entity name types for postgresql
        foreach (var entity in builder.Model.GetEntityTypes())
        {
                var tableName = builder.Entity(entity.Name).Metadata.GetTableName();

                if (!string.IsNullOrEmpty(tableName))
                {
                    if (tableName.Contains('<'))
                    {
                        tableName = tableName.Split('<')[0];
                    }

                    builder.Entity(entity.Name).ToTable(tableName.ToLower());
                }

                foreach (var index in entity.GetIndexes())
                {
                    if (!string.IsNullOrEmpty(index.Name))
                    {
                        index.SetDatabaseName(index.Name.ToLower());
                    }
                }
            }
    }
}

Is there a way to make the table names and not just the column names snake_case for Identity Framework? In the OnModelCreating code, I am converting all the tables and indices to lower case, but I was unaware if there is a more canonical strategy for accomplishing snake_case naming for the database schema than parsing upper and lowercase table and index names. Thanks in advance for any help!

2
  • 3
    Check the EFCore.NamingConventions package. The primary contributor is Shay Rojanski, the creator of NpgSql Commented Dec 2, 2024 at 15:46
  • 1
    UseSnakeCaseNamingConvention will not affect Identity tables, you need to manually name them. Eighter with [Table] attribute or ToTable() fluent API. Commented Dec 5, 2024 at 11:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.