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#驼峰命名法:
});
相关推荐
思麟呀6 小时前
在C++基础上理解CSharp-5
开发语言·c++·c#
z落落9 小时前
C#ToolStrip+StatusStrip 状态栏实时显示系统时间+NotifyIcon系统托盘
开发语言·c#
ctrl_v助手10 小时前
VisionPro (R) QuickBuild相机的连接
服务器·笔记·数码相机·c#
北域码匠11 小时前
奇偶归并排序:并行计算的排序利器
数据结构·算法·c#·排序算法
zhangfeng113312 小时前
国家超算中心 昆山站 异构加速卡1 显存16GB详细配置, 海光 Z100SM HCU
linux·网络·深度学习·c#
z落落12 小时前
C# WinForm TreeView 树形控件+ListView控件+菜单栏
开发语言·c#
ABprogramming13 小时前
Aspire入门指南
c#·.net
加号313 小时前
【C#】VS2022 传统 ASP.NET Web 服务(.asmx)接口实现指南
前端·c#·asp.net
加号31 天前
【C#】 文件与目录管理:创建、删除操作的技术解析
开发语言·c#
用户395240998801 天前
SqlSugar 连接 PostgreSQL 报错 42P01: relation does not exist 的排查与修复
c#