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

如何使用EF Core 6以自身用户访问Oracle中其他用户的数据库表?

在EF Core 6中访问Oracle其他用户的表

方法1:实体类上通过特性指定架构

Oracle中其他用户的表对应EF Core里的架构(Schema),直接在实体类上用[Table]特性指定目标用户作为架构:

using System.ComponentModel.DataAnnotations.Schema;

[Table("CUSTOMER", Schema = "IFSAPP")]
public class Customer
{
    // 对应CUSTOMER表的列属性
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    // 其他属性...
}

然后在DbContext中正常声明DbSet:

public DbSet<Customer> Customers { get; set; }

此时EF Core生成的SQL会自动带上IFSAPP.前缀,和你在SQL Developer中执行的查询逻辑一致。

方法2:在DbContext配置中指定架构

如果不想在实体类上添加特性,可在DbContext的OnModelCreating方法中单独配置实体的表和架构:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>()
        .ToTable("CUSTOMER", "IFSAPP");
    
    // 其他实体的配置逻辑...
}

方法3:全局设置默认架构(批量处理)

如果你的业务操作大部分针对IFSAPP用户下的表,可直接设置DbContext的默认架构,减少重复配置:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseOracle("你的Oracle连接字符串",
        o => o.MigrationsHistoryTable("__EFMigrationsHistory", "IFSAPP")); // 可选:将迁移历史表也放到IFSAPP用户下
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasDefaultSchema("IFSAPP");
    // 少数不属于IFSAPP的实体,再单独指定架构即可
}

验证生成的SQL

可以通过EF Core日志功能查看最终生成的SQL,比如执行dbContext.Customers.ToList()时,生成的语句应该类似:

SELECT "c"."CustomerId", "c"."CustomerName" FROM "IFSAPP"."CUSTOMER" AS "c"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:30:54