Asp-Net-Core开发笔记:EFCore统一实体和属性命名风格

前言

C# 编码规范中,类和属性都是大写驼峰命名风格(PascalCase / UpperCamelCase),而在数据库中我们往往使用小写蛇形命名(snake_case),在默认情况下,EFCore会把原始的类名和属性名直接映射到数据库,这不符合数据库的命名规范。

为了符合命名规范,而且也为了看起来更舒服,需要自己做命名转换处理。

FreeSQL的命名转换功能

FreeSQL 内置了很方便的命名风格转换功能,只需要设置 UseNameConvert 就可以实现 Pasca Case 到 snake_case 的转换。

c# 复制代码
var fsql = new FreeSqlBuilder()
  .UseConnectionString(DataType.MySql, Default.Value)
  .UseAutoSyncStructure(true)
  .UseNameConvert(NameConvertType.PascalCaseToUnderscoreWithLower)
  .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
  .Build();

EFCore 没有内置这个功能,需要我们自行实现。

使用正则实现命名风格转换

使用正则表达式可以实现这个功能

这里来写一个扩展方法

c# 复制代码
public static class StringExt {
    public static string ToSnakeCase(this string input) {
        if (string.IsNullOrEmpty(input)) {
            return input;
        }

        var startUnderscores = Regex.Match(input, @"^_+");
        return startUnderscores + Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower();
    }
}

这个方法会在每个小写字母/数字与大写字母之间添加下划线,并把整个字符串转换为小写。

修改 EFCore 行为

EFCore 有非常丰富的功能,修改表名和字段名当然也不在话下。

重写 DbContext 的 OnModelCreating 方法就行

c# 复制代码
public class AppDbContext : DbContext {
  // ...

  protected override void OnModelCreating(ModelBuilder modelBuilder) {
    base.OnModelCreating(modelBuilder);
    modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);

    // CamelCase to SnakeCase
    foreach (var entity in modelBuilder.Model.GetEntityTypes()) {
      // Replace table names
      if (!string.IsNullOrWhiteSpace(entity.GetTableName())) {
        entity.SetTableName(entity.GetTableName()!.ToSnakeCase());
      }

      // Replace column names            
      foreach (var property in entity.GetProperties()) {
        property.SetColumnName(property.GetColumnName().ToSnakeCase());
      }

      foreach (var key in entity.GetKeys()) {
        if (!string.IsNullOrWhiteSpace(key.GetName())) {
          key.SetName(key.GetName()!.ToSnakeCase());
        }
      }

      foreach (var key in entity.GetForeignKeys()) {
        if (!string.IsNullOrWhiteSpace(key.GetConstraintName())) {
          key.SetConstraintName(key.GetConstraintName()!.ToSnakeCase());
        }
      }

      foreach (var index in entity.GetIndexes()) {
        if (!string.IsNullOrWhiteSpace(index.GetDatabaseName())) {
          index.SetDatabaseName(index.GetDatabaseName()!.ToSnakeCase());
        }
      }
    }
  }
}

以上代码会对表名、列名、key、index的名称做转换。

搞定~

参考资料

相关推荐
Behavior1 小时前
Unity 7.0 Alpha 拆解:编辑器干掉 Mono 换 CoreCLR
c#·unity3d·游戏开发
淡海水2 小时前
02-06-原理篇-增量式GC与并发GC
算法·unity·c#·并发·gc·增量
Vertira2 小时前
C# 函数封装成 DLL,
开发语言·c#
浅尝辄止;4 小时前
设计模式在HIS/LIS医疗系统中的完整实践指南(C#版)
开发语言·设计模式·c#
kimloner14 小时前
开源一个 376KB 的 Windows 桌面小工具:便签 + 截图标注 + OCR + 待办提醒(C# / WinForms)
windows·开源·c#·ocr·winforms
阿松爱学习15 小时前
【Unity开发】Aspose.PDF的使用
unity·pdf·c#
半亩码田15 小时前
C#转Python第4.8篇:正则表达式:Python re 模块 vs C# System.Text.RegularExpressions
python·正则表达式·c#
FPGA小徐15 小时前
【一生一芯 / PA】异常响应机制:RISC-V 中 ecall → mtvec → mret 的完整代
开发语言·数据库·c#
淡海水16 小时前
02-04-原理篇-GC Roots与对象图遍历
算法·unity·c#·图·gc·遍历·roots
胖纸不争21 小时前
嫌桌面 Agent 太重,我“自己”写了一个
ai·c#·net core