EF Core使用CodeFirst生成postgresql数据库表名以及字段名用蛇形命名法,而类名仍使用驼峰命名

1、通过重写OnModelCreating来实现

复制代码
    public class SchedulerContext : DbContext
    {
        public SchedulerContext(DbContextOptions<SchedulerContext> options)
           : base(options)
        {

        }

        public DbSet<SysUserInfo> Users { get; set; }
        public DbSet<UserRole> UserRoles { get; set; }
        public DbSet<Permission> Permissions { get; set; }
        public DbSet<Modules> Modules { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<RoleModulePermission> RoleModulePermissions { get; set; }

        //已经改用EFCore.NamingConventions包的UseSnakeCaseNamingConvention,不需要再使用下面的代码
        //protected override void OnModelCreating(ModelBuilder modelBuilder)
        //{
        //    // 自动将实体类名和属性名转换为 snake_case
        //    foreach (var entity in modelBuilder.Model.GetEntityTypes())
        //    {
        //        // 表名转换(如 UserProfile -> user_profile)
        //        entity.SetTableName(ConvertToSnakeCase(entity.GetTableName()));

        //        // 列名转换(如 CreatedAt -> created_at)
        //        foreach (var property in entity.GetProperties())
        //        {
        //            property.SetColumnName(ConvertToSnakeCase(property.GetColumnName()));
        //        }

        //    }

        //}
        //private static string ConvertToSnakeCase(string input)
        //{
        //    if (string.IsNullOrEmpty(input)) return input;

        //    return Regex.Replace(input, "(?<=[a-z])([A-Z])", "_$1").ToLower();
        //}
    }
}

2、使用EFCore.NamingConventions

在NuGet包管理工具安装"EFCore.NamingConventions",然后在Program.cs类的连接数据库的位置加上UseSnakeCaseNamingConvention方法

复制代码
builder.Services.AddDbContext<SchedulerContext>(opt =>
{
    opt.UseNpgsql(builder.Configuration.GetConnectionString("SchedulerContext"))
        .UseSnakeCaseNamingConvention();//将PostgreSQL对蛇形命名法(snake_case)的默认映射方式改为C#驼峰命名法:
});
相关推荐
geovindu10 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
小羊先生car14 小时前
RTOS-F429-HAL-(动/静态)任务的创建(2026/7/27)
开发语言·算法·c#
地球驾驶员15 小时前
NX二次开发C#-获取体的外表面
开发语言·c#
向夏威夷 梦断明暄16 小时前
从 Bun 的 Rust 重写,看 C# 如何重建 AI 基础设施层
人工智能·rust·c#
心平气和量大福大17 小时前
C#-WPF-控件-LiveChart图表-线性2(LineSeries)-数据绑定
开发语言·c#·wpf
海盗123418 小时前
微软技术周报2026-07-27
microsoft·c#·.net
code bean1 天前
【C#】 `Channel<T>` 深度解析:生产者-消费者模式的现代解法
数据结构·c#
吴可可1231 天前
C# CAD二次开发:合并首尾重合多段线
c#
EIP低代码平台2 天前
EIP低代码平台 - 应用管理 - 表单设计
低代码·c#·权限·工作流·netcore
czhc11400756632 天前
726:zoffset
c#