ASP.NET Core MVC 使用 EF Core 实现实体属性驼峰转下划线

参考

  • DeepSeek
  • 豆包
  • 其他(由于文章是后编写的,相关参考文章未存储连接)

环境

软件/系统 版本 说明
Windows windows 10 专业版 22H2 64 位操作系统, 基于 x64 的处理器
Microsoft Visual Studio Community 2022 (64 位) - Current 版本 17.14.9
Visual Studio Code 1.102.2
Docker Engine v28.3.2 Docker 桌面工具
Docker 28.3.2
pgAdmin4 9.0 PostgreSQL 数据库管理软件
PostgreSQL 15
.NET 8
ASP.NET Core MVC ASP.NET Core MVC in .NET 8.0
Microsoft.EntityFrameworkCore.Design 8.0.18 nuget 依赖
Microsoft.EntityFrameworkCore.Tools 8.0.18 nuget 依赖
Npgsql.EntityFrameworkCore.PostgreSQL 8.0.11 nuget 依赖
EFCore.NamingConventions 8.0.3 nuget 依赖

本项目入口文件为 Program.cs ,创建项目时为不使用顶级语句

正文

  1. 安装 EFCore.NamingConventions
  2. 修改 Program.csbuilder.Services.AddDbContext 位置相关代码如下:
    // Add services to the container.
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
    builder.Services.AddDbContext<ApplicationDbContext>(
    	options =>
    	{
    		// 配置模型与数据库转换,基于 EFCore.NamingConventions
    		options.UseNpgsql(connectionString).UseSnakeCaseNamingConvention();
    	});
    
  3. 实体定义
  4. 创建迁移、运行迁移即可。

预览

  • 模型参考
    image
  • 生成结果参考
    image
posted @ 2025-07-27 17:40  夏秋初  阅读(33)  评论(0)    收藏  举报