曦远 (DealiAxy)一份私人的文字刊物

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开发笔记:接口返回json对象出现套娃递归问题

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

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

讨论

共 0 条

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

加载评论中…