【问题标题】:EF core code first migrations automatically prefixing Tables with db_ownerEF 核心代码首先迁移自动为表添加 db_owner 前缀
【发布时间】:2018-11-28 20:20:02
【问题描述】:

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

dotnet ef database update

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

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

【问题讨论】:

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


    【解决方案1】:

    您可以在 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"]);
        }
    }
    

    【讨论】:

    • 是的,实际上当我在 localhost 上执行此操作时,它默认使用 dbo,默认情况下在我的 vm 服务器上使用 dbowner。明天我会先试一试,然后回复你
    • 这非常简单,令人惊讶的是,我在 EF 文档中找不到它。谢谢!
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多