lockworld
6/6/2019 - 3:28 AM

Entity Framework Tips and Tricks

/*
If you are using a custom schema for your DbContext, you need to tell Entity Framework where to look for the migraton history table in order to use code-first data migratios. To do this, create a new HistoryContext class as follows.

Failure to do this wll result in the following Package Manager error:
  Automatic migrations that affect the location of the migrations history system table (such as default schema changes) are not supported. Please use code-based migrations for operations that affect the location of the migrations history system table.
*/

using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Migrations.History;

namespace MyApp
{
  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: "me");
        modelBuilder.Entity<HistoryRow>().Property(p => p.MigrationId).HasColumnName("MigrationId");
    }
  }
}

/*
Reference: https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/history-customization
*/