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#驼峰命名法:
});
相关推荐
Nuopiane1 天前
C#基础(1)堆栈、GC与Marshal
unity·c#
FuckPatience1 天前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
游乐码1 天前
c#泛型约束
开发语言·c#
hoiii1871 天前
C# 基于 LumiSoft 实现 SIP 客户端方案
前端·c#
yongui478341 天前
C# 与三菱PLC通讯解决方案
开发语言·c#
jerryinwuhan2 天前
RDD第二次练习
开发语言·c#
aini_lovee2 天前
C# 快速搜索磁盘文件解决方案
开发语言·c#
派葛穆2 天前
汇川PLC-Unity3d与汇川easy521plc进行Modbustcp通讯
unity·c#
游乐码2 天前
C#List
开发语言·c#·list
Paine Zeng2 天前
C# + SolidWorks 二次开发 -监听退出草图事件并自动执行逻辑
c#·solidworks二次开发·solidworks api