You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Entity Framework Core使用方括号而非引号包裹标识符?

解决EF Core 7连接Oracle时标识符格式问题

方案1:生成不带双引号的标识符(推荐,符合Oracle默认不区分大小写逻辑)

Oracle.EntityFrameworkCore默认会给标识符加双引号,导致区分大小写。只需在配置DbContext时关闭引号处理:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseOracle("你的Oracle连接字符串", options =>
    {
        options.UseQuotedIdentifiers(false);
    });
}

配置后EF生成的SQL会直接用Schema.Table这种格式,Oracle会自动把标识符转成大写,且不区分大小写,完全满足你的需求。

方案2:自定义生成方括号包裹的标识符(需数据库端配合)

如果你一定要用方括号格式,需要三步操作:

1. 自定义SQL生成帮助类

继承Oracle的SQL生成助手,重写标识符分隔方法:

using Microsoft.EntityFrameworkCore.Storage;
using Oracle.EntityFrameworkCore.Storage;

public class BracketedOracleSqlHelper : OracleSqlGenerationHelper
{
    public BracketedOracleSqlHelper(RelationalSqlGenerationHelperDependencies dependencies)
        : base(dependencies)
    {
    }

    // 处理单个标识符
    public override string DelimitIdentifier(string identifier)
    {
        return $"[{identifier}]";
    }

    // 处理带架构的标识符
    public override string DelimitIdentifier(string identifier, string schema)
    {
        if (string.IsNullOrWhiteSpace(schema))
        {
            return DelimitIdentifier(identifier);
        }
        return $"{DelimitIdentifier(schema)}.{DelimitIdentifier(identifier)}";
    }
}

2. 在DbContext中替换服务

把默认的SQL生成服务换成自定义的:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseOracle("你的Oracle连接字符串")
                  .ReplaceService<ISqlGenerationHelper, BracketedOracleSqlHelper>();
}

3. 数据库端开启方括号支持

Oracle默认不认方括号,需要执行语句开启兼容设置:

-- 会话级生效
ALTER SESSION SET SQL_IDENTIFIER_QUOTING = 'BRACKET';

-- 全局生效(需DBA权限)
ALTER SYSTEM SET SQL_IDENTIFIER_QUOTING = 'BRACKET' SCOPE=SPFILE;

注:该设置仅支持Oracle 12c及以上版本。

内容的提问来源于stack exchange,提问作者relatively_random

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 15:53:32