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#驼峰命名法:
});
相关推荐
逝水无殇1 小时前
C# 枚举(Enum)详解
开发语言·后端·c#
影寂ldy3 小时前
C# WinForms 窗体继承
开发语言·c#
苍狼唤16 小时前
WinForm练习知识补充(多线程)
c#
逝水无殇19 小时前
C# 字符串(String)详解
开发语言·后端·c#
小巧的砖头21 小时前
C#会重蹈覆辙吗?系列之2:反射及元数据的性能问题
开发语言·前端·c#
医疗信息化王工1 天前
从零到一:基于 GGUF 格式部署 Unlimited-OCR 搭建企业级证件识别服务
图像处理·c#·ocr
zyh______1 天前
C#语法糖(按照实用性排序)
unity·c#
z落落1 天前
C#五大加密算法(AES、DES、MD5、RSA、SHA)
开发语言·c#
孝顺的书包1 天前
将《C# 调用非托管程序》一文中最后一种方法修改如下(篇幅原因简化了注释):
开发语言·c#
辰三1 天前
统信 UOS + GBase 8s 国产化环境部署实战:从虚拟机到数据库连接完整指南
linux·c#