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开发笔记:集成Hangfire实现异步任务队列和定时任务
前言 最近把Python写的数据采集平台往.Net Core上迁移,原本的采集任务使用多进程+线程池的方式来加快采集速度,使用Celery作为异步任务队列兼具定时任务功能,这套东西用着还行,但反正就折腾嘛,直接上C#~ 本文记录 Hangfire 在实际应用里的用法,我发现网络上找到的大部分文章都是用 Hangfire 的异步任务输出个 Hello World,然后就没了。我实在不知道这样的文章写
2023-03-09 · Asp-Net-Core开发笔记 · 约 1 分钟
Asp-Net-Core开发笔记:使用NPM和gulp管理前端静态文件
前言 本文介绍的是AspNetCore的MVC项目,WebApi+独立前端这种前后端分离的项目就不需要多此一举了~默认前端小伙伴是懂得使用前端工具链的。 为啥要用MVC这种服务端渲染技术呢? 简单项目不需要强行分离增加复杂度(如:我正在开发的博客项目) 后端渲染利于SEO,对博客网站友好 OK,虽然MVC的技术老了点,但依然可以结合现代前端工具链来提高效率 本文的食用需要先安装好Node.js环境
2022-02-17 · 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 分钟
AspNetCore开发笔记:WebApi项目集成企业微信和公众号
微信开发文档烂得离谱,直接用SKIT库搞定。异步处理消息,图片下载内存处理,公众号被动回复5秒内搞定。啧啧。
2025-12-22 · Asp-Net-Core开发笔记 · 约 1 分钟
讨论
共 0 条加载评论中…