Things to take care while working with EF Code First

  • Code First Can be enabled for existing db or blank db
  • Command for enabling Code First
    • Enabled-Migrations
      • This will generate Migration Folder and Migration Configuration File where by default automaticmigration will be false.
      • Many people consider to change that as that will not apply pending changes to database automatically
      • When we do have change in model but we forget to add migration and update database manually, above option will automatically generate migration script and apply it to database
      • In most of the cases its good, but would not recommend as in some cases of migration script like adding column to existing tables without default value
        • Here system will generate basic script without default values
        • System will fail to apply database update.
        • Now we need to manually edit generated script file or apply changes in database manually using script and even add migration history also
          • For Manual editing or generate script, in case of vs MVC project Yet to find that stuff.
          • for manual updating to db another hard part forget it.
          • Solution:revert change and start again
      • Instead of AutomaticMigration = True, we will use option to
        • Generate Migrations manually
        • Run those Pending migrations manually or automatic
        • If we forget to generate migrations manually system will stop generating error “Model doesn’t match database” which is good for us
    • Add-Migration “Migration Name” [For Blank Project]
      • This will generate code for adding respective tables as per your POCO Classes
    • Add-Migration “Migration Name” -IgnoreChanges
      • Here we should note that our POCO Classes should exactly match existing db model as it will generate completely blank migration which will just accept current db structure same as POCO Classes
    • Update-Database -script
      • This Command will generate sql script file which can be used to manual update in case of auto migration fails
    • Update-Database -Verbose
      • This command will update respective connecting/active database which is usually development database
      • Here we need to consider that we still need to apply those migration updates to our production database too

Our Sample Migration Configuration Class Code:


using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Linq;
namespace BIS.DAL.DatabaseContext
    internal sealed class EFMigrationConfiguration : DbMigrationsConfiguration<IdentityEntities>
        public EFMigrationConfiguration()
            AutomaticMigrationsEnabled = false;
            AutomaticMigrationDataLossAllowed = true;
            ContextKey = "IdentityEntities";
        protected override void Seed(IdentityEntities context)
            //use db migrator to generate pending code based migrations and apply it explicitly 
            var configuration = new EFMigrationConfiguration();
            var migrator = new DbMigrator(configuration);
            IList<string> AppliedMigrations = migrator.GetDatabaseMigrations().ToList();
            IList<string> PendingMigrations = migrator.GetPendingMigrations().ToList();
            string cPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Private", "Migrations");
            if (!System.IO.Directory.Exists(cPath)) { System.IO.Directory.CreateDirectory(cPath); }
            string fPath = System.IO.Path.Combine(cPath, $"Migration_{DateTime.Now.ToString("yyyyMMdd")}.txt");
            MigratorScriptingDecorator scripter = new MigratorScriptingDecorator(migrator);
            string script = scripter.ScriptUpdate(null, null);
            if (script != null && script.Length > 0)
                System.IO.File.AppendAllText(fPath, script);

Our Sample IdentityEntities Model Class Constructor


public IdentityEntities() : base("IdentityConnection")
{    Database.SetInitializer(new MigrateDatabaseToLatestVersion<IdentityEntities, EFMigrationConfiguration>("IdentityConnection"));