From 685470ab797148dd681d09a5756c7f3b902198f2 Mon Sep 17 00:00:00 2001 From: hello Date: Fri, 22 Nov 2024 22:08:05 +0800 Subject: [PATCH] =?UTF-8?q?=E5=91=BD=E5=90=8D=E8=A7=84=E8=8C=83=E7=BA=A6?= =?UTF-8?q?=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- notes/helloshop/efcore-naming-conventions.md | 69 ++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 notes/helloshop/efcore-naming-conventions.md diff --git a/notes/helloshop/efcore-naming-conventions.md b/notes/helloshop/efcore-naming-conventions.md new file mode 100644 index 0000000..abada0a --- /dev/null +++ b/notes/helloshop/efcore-naming-conventions.md @@ -0,0 +1,69 @@ +# 数据库对象命名约定 + +不同数据库对象的命名约定不同,EF Core 为了适配不同数据库,提供了一些命名约定的配置选项。 + +## 手动指定表名和列名 + +### 表名 + +默认情况下,EF Core 使用实体类型的名称作为表名。可以通过重写 `OnModelCreating` 方法来修改表名: + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity().ToTable("blogs"); +} +``` + +### 列名 + +默认情况下,EF Core 使用属性名作为列名。可以通过 `HasColumnName` 方法来修改列名: + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity().Property(b => b.Url).HasColumnName("blog_url"); +} +``` + +## PostgreSQL 命名约定 + +PostgreSQL 的命名约定采用小写蛇形命名法,即单词之间使用下划线分隔,如 `blog_url`,表名使用单数形式。 + +## 使用 EFCore.NamingConventions 库 + +EFCore.NamingConventions 库提供了一些命名约定的配置选项,可以方便地配置表名、列名等。 + +### 安装 EFCore.NamingConventions 库 + +```bash +dotnet add package EFCore.NamingConventions +``` + +### 配置命名约定 + +使用 OnConfiguring 方法配置命名约定: + +```csharp +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) +{ + base.OnConfiguring(optionsBuilder); + optionsBuilder.UseSnakeCaseNamingConvention(); +} +``` + +或者在依赖注入容器中配置: + +```csharp +builder.Services.AddDbContext(options => options.UseNpgsql().UseSnakeCaseNamingConvention()); +``` + +### 修改迁移历史表名 + +默认情况下,EF Core 在名为 __EFMigrationsHistory 的表中记录哪些迁移已应用到数据库中,从而跟踪这些迁移。 出于各种原因,可能需要自定义此表,以更好地满足你的需求。 + +```csharp +options.UseSqlServer(connectionString,x => x.MigrationsHistoryTable("__MyMigrationsHistory", "mySchema")); +``` + +https://learn.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/history-table