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.
目录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:
FullNamebecomesfull_name - UseLowerCaseNamingConvention:
FullNamebecomesfullname - UseCamelCaseNamingConvention:
FullNamebecomesfullName - UseUpperCaseNamingConvention:
FullNamebecomesFULLNAME - UseUpperSnakeCaseNamingConvention:
FullNamebecomesFULL_NAME
References
_EOF_
ASP.NET Core Development Notes: Standardizing Entity and Property Naming Conventions with EFCore
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
Asp-Net-Core开发笔记:API版本管理
对于Web API应用程序而言,随着时间的推移以及需求的增加或改变,API必然会遇到升级的需求。事实上,Web API应用程序应该从创建时就考虑到API版本的问题。业务的调整、功能的增加、接口的移除与改名、接口参数变动、实体属性的添加、删除和更改等都会改变API的功能,从而带来版本的变更。
2023-06-09 · Asp-Net-Core开发笔记 · 约 1 分钟
Asp-Net-Core开发笔记:使用ActionFilterAttribute实现非侵入式的参数校验
用ActionFilterAttribute搞非侵入校验,省得重复写代码。支持Query、Body、Route、Header,HttpContext共享数据,但OAuth2.0边学边做,项目乱糟糟,功能凑合。
2024-05-17 · Asp-Net-Core开发笔记 · 约 1 分钟
Asp-Net-Core开发笔记:Oracle调优
Supported Connection String Attributes To obtain an OracleConnection object in a .NET stored procedure that represents the implicit database connection, set the ConnectionString property of the Oracle
2023-03-05 · Asp-Net-Core开发笔记 · 约 1 分钟
Asp-Net-Core开发笔记:接口返回json对象出现套娃递归问题
前言 看了下推送记录,一个月前,OK,我又变成月更了o(╯□╰)o,这绝对不行![○・`Д´・ ○] 所以今天来更新了 其实不是我懒得更新或者是太忙,其实是最近在写一篇很长的博客,一直没写完( Ĭ ^ Ĭ ) 好吧,先进入正题…… 有一个关于WebApi序列化的问题,跟设计有关,但在涉及到关联字段的时候经常会遇到。 实体类 先看看实体类定义,限于篇幅,只保留几个关键字段。 public class
2022-02-16 · Asp-Net-Core开发笔记 · 约 1 分钟
讨论
共 0 条加载评论中…