首页 > 解决方案 > EF 核心代码首先迁移自动为表添加 db_owner 前缀

问题描述

我目前正在使用 EF Core 2.1 代码优先迁移来创建我的 SQL 服务器架构。当我使用以下命令在 SQL Server 中创建/更新我的表时”

dotnet ef database update

它在我的表前面加上“db_owner”。例如“db_owner.drivers”。

有没有办法在代码中从我的 ef 配置文件中设置 db 前缀名称?或者这是在 SQL Server 本身中实际配置的东西?

标签: sqlsql-serverentity-frameworkasp.net-coreentity-framework-core

解决方案


您可以ToTable在 dbContext 中使用来设置方案名称,如果您未指定,EF 核心将按dbo约定使用。

 public class MyDbContext
 {
   private string schemaName = "MyPrefix";
   protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntity>().ToTable("MyTable", schemaName );
    }
 }   

如果您想在配置文件(appsettings.json)中设置 schemaName:

{
  "schemaName": "MyPrefix",
}

您可以使用 DI 在 dbContext 文件中获取配置。

public class MyDbContext
{
    private readonly IConfiguration _configuration;     
    public MyDbContext(DbContextOptions<ApplicationDbContext> options, IConfiguration configuration)
        : base(options)
    {
        _configuration = configuration;
    }

    ...// DbSet<>

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntity>().ToTable("MyTable", _configuration["schemaName"]);
    }
}

推荐阅读