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

namespace CustomMigrationHistory.Context
{
    /// <summary>
    /// This class is used to define what you want to
    /// customize in "__MigrationHistory" Table
    /// </summary>
    public class CustomHistoryContext : HistoryContext
    {
        public CustomHistoryContext(DbConnection dbConnection, string defaultSchema) 
            : base(dbConnection, defaultSchema) 
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            // Renaming "__MigrationHistory" table to "DbOperations"
            modelBuilder.Entity<HistoryRow>().ToTable(tableName: "DbOperations");

            // IMPORTANT
            // Once we rename the "__MigrationHistory" table it becomes mandatory to control the Composite Primary key length of the table
            // Actian Zen Server has length limitation for Primary key
            // If Unicode is enabled the cumulative length of primary keys should be lesser than or equals to 125
            // If Unicode is not enabled the cumulative length of primary keys should be lesser than or equals to 254
            // From EF6 onwards to support Multiple Context EF has made 'MigrationId' and 'ContextKey' (newly introduced in EF6)
            //  combined as the Composite Primary Key for Migration History Table.
            // Hence combined length of 'MigrationId' and 'ContextKey' has to lesser than 254. (125 for Unicode databases)
            modelBuilder.Entity<HistoryRow>().Property(p => p.MigrationId).HasColumnName("MigrationKey").HasMaxLength(40);
            modelBuilder.Entity<HistoryRow>().Property(p => p.ContextKey).HasColumnName("DbContextKey").HasMaxLength(85);
        }
    }
}
