EF核心代码优先迁移会自动为表添加db_owner前缀

时间:2018-11-28 20:20:03

标签: sql sql-server entity-framework asp.net-core entity-framework-core

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

dotnet ef database update

它为我的表添加了“ db_owner”前缀。例如“ db_owner.drivers”。

有没有办法在代码中通过我的ef配置文件设置数据库前缀名称?还是这实际上是在SQL Server本身中配置的?

1 个答案:

答案 0 :(得分:3)

您可以在dbContext中使用ToTable来设置方案名称,如果未指定,则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"]);
    }
}