EF Core 8 Code First创建Oracle表时避免双引号查询
如何让EF Core生成无需双引号即可查询的Oracle表?
背景
我定义了如下实体类:
public class Book { [Key] public Guid Id { get; set; } public string Name { get; set; } = default!; public string Author { get; set; } = default!; public int Pages { get; set; } = default!; }
执行迁移命令创建表:
dotnet ef migrations add AddBooks -p .\MyApplication.Infrastructure\ -s .\MyApplication.API\ dotnet ef database update
表创建成功后,使用select * from Books b查询时提示"Table or view does not exist",只有带双引号的select * from "Books" b能正常查询,和其他表的查询方式不一致。
问题原因
Oracle数据库的核心特性:不带双引号的标识符(表名、列名)会被自动转换为大写存储。而EF Core默认会以实体类的PascalCase名称(比如Books)作为表名,并且用双引号包裹来保留大小写,导致实际创建的表名是区分大小写的Books,查询时必须带双引号才能匹配。
解决方案
1. 为单个实体显式配置大写表名
在你的DbContext的OnModelCreating方法中,为Book实体指定大写的表名:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Book>() .ToTable("BOOKS"); }
修改后重新生成迁移并更新数据库:
dotnet ef migrations add UpdateBookTableName -p .\MyApplication.Infrastructure\ -s .\MyApplication.API\ dotnet ef database update
此时表名会被创建为大写的BOOKS,查询时使用select * from Books b或select * from BOOKS b都能正常执行(Oracle会自动把不带引号的Books转为大写)。
2. 全局配置所有实体的表名为大写
如果希望所有实体对应的表名都自动转为大写,避免逐个配置,可以在OnModelCreating中添加全局约定:
protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { var currentTableName = entityType.GetTableName(); if (!string.IsNullOrEmpty(currentTableName)) { entityType.SetTableName(currentTableName.ToUpper()); } } }
同样需要重新生成迁移并更新数据库,之后所有新创建的表都会使用大写名称,查询时无需带双引号。
内容的提问来源于stack exchange,提问作者kbd
相关产品推荐
相关产品推荐

