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#驼峰命名法:
});
相关推荐
yngsqq2 小时前
平面图环 内轮廓
c#
rockey6274 小时前
AScript之eval函数详解
c#·.net·script·eval·expression·动态脚本
He少年8 小时前
【AI 辅助案例分享】
人工智能·c#·编辑器·ai编程
工程师00710 小时前
栈和堆的概念
c#·栈和堆
不会编程的懒洋洋10 小时前
C# P/Invoke 基础
开发语言·c++·笔记·安全·机器学习·c#·p/invoke
Avalon71210 小时前
Unity3D响应式渲染UI框架UniVue
游戏·ui·unity·c#·游戏引擎
njsgcs11 小时前
solidworks折弯自动标注5 非90度折弯
c#·solidworks
狼与自由11 小时前
clickhouse引擎
clickhouse·c#·linq
wangnaisheng12 小时前
【C#】死锁详解:发生原因、优化解决方案
c#
tiger从容淡定是人生12 小时前
AI替代软件战略(一):从 CCleaner 到 MCP 架构重构 —— TigerCleaner 的工程实践
人工智能·重构·架构·c#·mcp