EF 6 Code First __MigrationHistory in dbo schema by default

对着背影说爱祢 提交于 2019-12-23 04:10:26

问题


I am new to Code first Entity framework, when logging into the database after running my app for the first time I got a little confused when I saw the "__MigrationHistory" table.

I now understand the need for this table, but do not like it being in the standard dbo schema within the user table, I think its obtrusive and a risk.

My first thought was to move it to the system folder. When researching how to achieve this within the EF context all I could find is how to move it from system to dbo.

I now get the feeling __MigrationHistory should by default be created within the system folder... is this the case?

How can I configure my context to manage/reference the migration history table within the system folder by default?

Here is my context, am I doing something wrong or missing some configuration?

public class MyContext : DbContext, IDataContext
{
    public IDbSet<Entity> Entities { get; set; }

    public MyContext()
        : base("ConnectionString")
    {

    }

    public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
    {
        return base.Set<TEntity>();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

回答1:


There is a technique for moving __MigrationHistory. That table has it's own context (System.Data.Entity.Migrations.History.HistoryContext) that you can override:

public class MyHistoryContext : HistoryContext 
{ 
    public MyHistoryContext(DbConnection dbConnection, string defaultSchema) 
        : base(dbConnection, defaultSchema) 
    { 
    } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
        base.OnModelCreating(modelBuilder); 
        modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistory", schemaName: "admin"); 
        modelBuilder.Entity<HistoryRow>().Property(p => p.MigrationId).HasColumnName("Migration_ID"); 
    } 
} 

Then you need to register it:

public class ModelConfiguration : DbConfiguration 
{ 
    public ModelConfiguration() 
    { 
        this.SetHistoryContext("System.Data.SqlClient", 
            (connection, defaultSchema) => new MyHistoryContext(connection, defaultSchema)); 
    } 
} 



回答2:


You could try executing EXEC sys.sp_MS_marksystemobject __MigrationHistory in your seed method using context.Database.ExecuteSqlCommand();



来源:https://stackoverflow.com/questions/28355352/ef-6-code-first-migrationhistory-in-dbo-schema-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!