返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Asp-Net-Core开发笔记

ASP.NET Core Development Notes: Standardizing Entity and Property Naming Conventions with EFCore

I can't believe EFCore doesn't have built-in naming conventions? You have to write regex yourself or use a plugin, what a hassle. The plugin can do it in one line of code, but why doesn't EFCore directly support it? For naming style conversion, you either write the code yourself or rely on third parties, what a chore.

曦远 (DealiAxy)约 12 分钟
目录7 个章节

Preface

In C# coding conventions, classes and properties follow PascalCase (UpperCamelCase) naming style, while in databases we often use snake_case. By default, EFCore directly maps the original class and property names to the database, which does not comply with database naming conventions.

To adhere to naming standards and also for better readability, custom naming conversion processing is required.

FreeSQL's Naming Conversion Feature

FreeSQL has a built-in convenient naming style conversion feature that can be implemented simply by setting UseNameConvert, enabling conversion from PascalCase to snake_case.

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

EFCore does not have this feature built-in, so we need to implement it ourselves.

Implementing Naming Style Conversion with Regular Expressions

Using regular expressions can achieve this functionality.

Here, we'll write an extension method.

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();
    }
}

This method adds an underscore between each lowercase letter or digit and an uppercase letter, and converts the entire string to lowercase.

Modifying EFCore Behavior

EFCore is feature-rich, and changing table and field names is naturally well within its capabilities.

Simply override the OnModelCreating method of your DbContext.

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());
        }
      }
    }
  }
}

The code above will convert the names of tables, columns, keys, and indexes.

Done~

Extension: Implementing Name Conversion Using Plugins

2023-10-10 addendum: After this article was published on the blog, a fellow developer shared the EFCore.NamingConventions plugin, which can conveniently implement naming style conversions.

Project address: https://github.com/efcore/EFCore.NamingConventions

Usage

First, install the EFCore.NamingConventions NuGet package.

Then, override the OnConfiguring method of DbContext.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
  base.OnConfiguring(optionsBuilder);
  optionsBuilder.UseSnakeCaseNamingConvention();
}

Name conversion can be achieved with just one line of code.

This plugin supports conversion to multiple styles simultaneously. Simply call different extension methods.

  • UseSnakeCaseNamingConvention: FullName becomes full_name
  • UseLowerCaseNamingConvention: FullName becomes fullname
  • UseCamelCaseNamingConvention: FullName becomes fullName
  • UseUpperCaseNamingConvention: FullName becomes FULLNAME
  • UseUpperSnakeCaseNamingConvention: FullName becomes FULL_NAME

References

_EOF_

ASP.NET Core Development Notes: Standardizing Entity and Property Naming Conventions with EFCore

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

Asp-Net-Core开发笔记:使用RateLimit中间件实现接口限流

前言 最近一直在忙(2月份沉迷steam,3月开始工作各种忙),好久没更新博客了,不过也积累了一些,忙里偷闲记录一下。 这个需求是这样的,我之前做了个工单系统,现在要对登录、注册、发起工单这些功能做限流,不能让用户请求太频繁。 从 .Net7 开始,已经有内置的限流功能了,但目前我们的项目还在使用 .Net6 LTS 版本,下一个 LTS 没发布之前,暂时不考虑使用 .Net7 这种非 LTS 版

2023-03-20 · Asp-Net-Core开发笔记 · 约 1 分钟

Asp-Net-Core开发笔记:集成Hangfire实现异步任务队列和定时任务

前言 最近把Python写的数据采集平台往.Net Core上迁移,原本的采集任务使用多进程+线程池的方式来加快采集速度,使用Celery作为异步任务队列兼具定时任务功能,这套东西用着还行,但反正就折腾嘛,直接上C#~ 本文记录 Hangfire 在实际应用里的用法,我发现网络上找到的大部分文章都是用 Hangfire 的异步任务输出个 Hello World,然后就没了。我实在不知道这样的文章写

2023-03-09 · Asp-Net-Core开发笔记 · 约 1 分钟

Asp-Net-Core开发笔记:快速在已有项目中引入EFCore

很多项目一开始选型的时候没有选择EFCore,不过EFCore确实好用,也许由于种种原因后面还是需要用到,这时候引入EFCore也很方便。 本文以 StarBlog 为例,StarBlog 目前使用的 ORM 是 FreeSQL ,引入 EFCore 对我来说最大的好处是支持多个数据库,如果是 FreeSQL 的话,服务注册的时候是单例模式,只能连接一个数据库,如果需要使用 FreeSQL 同时

2023-10-08 · Asp-Net-Core开发笔记 · 约 1 分钟

Asp-Net-Core开发笔记:接口返回json对象出现套娃递归问题

前言 看了下推送记录,一个月前,OK,我又变成月更了o(╯□╰)o,这绝对不行![○・`Д´・ ○] 所以今天来更新了 其实不是我懒得更新或者是太忙,其实是最近在写一篇很长的博客,一直没写完( Ĭ ^ Ĭ ) 好吧,先进入正题…… 有一个关于WebApi序列化的问题,跟设计有关,但在涉及到关联字段的时候经常会遇到。 实体类 先看看实体类定义,限于篇幅,只保留几个关键字段。 public class

2022-02-16 · Asp-Net-Core开发笔记 · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…

ASP.NET Core Development Notes: Standardizing Entity and Property Naming Conventions with EFCore · StarBlog