Showing posts with label Entity Framework. Show all posts
Showing posts with label Entity Framework. Show all posts

Friday, 19 December 2025

How to Migrate in EF Core Without Data Loss

 This is a very important real-time EF Core question.

Let’s break it down clearly, practically, and safely, exactly how it’s done in production systems.


How to Migrate in EF Core Without Data Loss

(Adding / Removing Columns Safely)


Golden Rule (Interview Answer)

EF Core migrations never delete data unless you explicitly tell them to.
Data loss happens only when:

  • You drop a column/table

  • You change data type incorrectly

  • You don’t provide defaults for non-nullable columns


1️⃣ Adding a Column WITHOUT Data Loss (Safe Way)

Scenario

Existing Users table already has data.
Now you want to add a new column.


✅ Case 1: Add Nullable Column (Safest)

public string PhoneNumber { get; set; }

Migration generated

migrationBuilder.AddColumn<string>(
    name: "PhoneNumber",
    table: "Users",
    nullable: true);

✔️ No data loss
✔️ Existing rows remain untouched

👉 Recommended approach


✅ Case 2: Add Non-Nullable Column (Correct Way)

public bool IsActive { get; set; }

❌ This will fail if table already has rows.

✔️ Correct Solution – Provide Default Value

migrationBuilder.AddColumn<bool>(
    name: "IsActive",
    table: "Users",
    nullable: false,
    defaultValue: true);

✔️ Existing rows get default value
✔️ No data loss


🚫 WRONG WAY

public bool IsActive { get; set; } // no default

❌ Migration fails
❌ Causes runtime exception


2️⃣ Removing a Column WITHOUT Data Loss (Safe Strategy)

Important Truth

Dropping a column ALWAYS deletes data
There is no automatic safe delete.

So how do real projects do it?


✅ Strategy 1: Soft Remove (Recommended)

Instead of deleting column:

public bool IsDeprecated { get; set; }

✔️ Column remains
✔️ App stops using it
✔️ Data preserved


✅ Strategy 2: Two-Step Migration (Production Safe)

Step 1: Backup Data

SELECT OldColumn INTO Users_OldColumn_Backup FROM Users;

Step 2: Drop Column

migrationBuilder.DropColumn(
    name: "OldColumn",
    table: "Users");

✔️ No business data lost
✔️ Recoverable if needed


✅ Strategy 3: Move Data Before Removing Column

migrationBuilder.Sql(
    "UPDATE Users SET NewColumn = OldColumn");

Then drop old column.

✔️ Data preserved
✔️ Schema cleaned


3️⃣ Renaming Column (Common Data Loss Mistake)

❌ Wrong Way

public string MobileNumber { get; set; } // renamed from PhoneNumber

EF Core thinks:

  • Drop PhoneNumber

  • Add MobileNumber

➡️ ❌ DATA LOSS


✅ Correct Way – Rename Column

migrationBuilder.RenameColumn(
    name: "PhoneNumber",
    table: "Users",
    newName: "MobileNumber");

✔️ Data retained
✔️ Safe migration


4️⃣ Changing Column Data Type (Safely)

❌ Risky

public int Age { get; set; } // previously string

✅ Safe Migration

migrationBuilder.Sql(
    "UPDATE Users SET Age = TRY_CAST(Age AS INT)");

Then change column type.

✔️ Converts data
✔️ Prevents failure


5️⃣ Best Practices to Avoid Data Loss (Real-World)

✔️ Always review migration script

dotnet ef migrations script

✔️ Take DB backup before prod migration

✔️ Never use EnsureCreated() in prod

✔️ Avoid auto-migrate on app startup

✔️ Use feature-based migrations


6️⃣ Real Interview Answer (Concise)

To migrate without data loss in EF Core, we add nullable or default-valued columns, rename columns using RenameColumn, migrate data using SQL before dropping columns, and never delete schema elements directly in production without backup.


7️⃣ Quick Safety Checklist

OperationSafe?How
Add columnNullable or default
Rename columnRenameColumn
Remove columnBackup or soft delete
Change type⚠️Data conversion SQL
Drop tableArchive first

If you want next:

  • 🔥 Zero-downtime production migration

  • 🔥 Blue-green DB migration strategy

  • 🔥 EF Core migration rollback

  • 🔥 Handling huge tables (millions of rows)

  • 🔥 Migration interview questions

Just say the word 👍

Entity Framework core code first migration steps in detailed with example

 Below is a very detailed, step-by-step explanation of EF Core Code-First migrations with a complete real-time example, exactly how it’s expected in enterprise projects and interviews.


EF Core Code-First Migration – Detailed Steps with Example


What is Code-First in EF Core?

Code-First means:

  • You design C# entities first

  • EF Core generates the database schema

  • Migrations track schema changes over time

Database = output
C# code = source of truth


Real-Time Scenario

We are building a User Management API.

Initial Requirements

  • Create Users table

  • Later add Email, DateOfBirth, IsActive


Step 1: Create Web API Project

dotnet new webapi -n UserManagement.API
cd UserManagement.API

Step 2: Install Required Packages

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

📌 Tools is mandatory for migrations


Step 3: Create Entity Classes (Models)

📁 Entities/User.cs

using System.ComponentModel.DataAnnotations;

public class User
{
    [Key]
    public int Id { get; set; }

    [Required]
    [MaxLength(100)]
    public string Name { get; set; }

    [MaxLength(200)]
    public string Email { get; set; }

    public DateTime DateOfBirth { get; set; }

    public bool IsActive { get; set; }
}

Step 4: Create DbContext

📁 Data/AppDbContext.cs

using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .Property(x => x.IsActive)
            .HasDefaultValue(true);
    }
}

Step 5: Configure Connection String

📁 appsettings.json

"ConnectionStrings": {
  "DefaultConnection": "Server=.;Database=UserManagementDb;Trusted_Connection=True;TrustServerCertificate=True"
}

Step 6: Register DbContext (Program.cs)

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));

Step 7: Add Initial Migration

dotnet ef migrations add InitialCreate

What EF Core Does

✔️ Scans entity classes
✔️ Compares model vs empty database
✔️ Generates migration files


Generated Migration (Simplified)

📁 Migrations/xxxx_InitialCreate.cs

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Users",
        columns: table => new
        {
            Id = table.Column<int>(nullable: false)
                .Annotation("SqlServer:Identity", "1, 1"),
            Name = table.Column<string>(maxLength: 100, nullable: false),
            Email = table.Column<string>(maxLength: 200, nullable: true),
            DateOfBirth = table.Column<DateTime>(nullable: false),
            IsActive = table.Column<bool>(nullable: false, defaultValue: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Users", x => x.Id);
        });
}

Step 8: Apply Migration to Database

dotnet ef database update

✔️ Database created
✔️ Tables created
✔️ __EFMigrationsHistory table created


Step 9: Change Entity (New Business Requirement)

Add PhoneNumber field.

📁 User.cs

[MaxLength(15)]
public string PhoneNumber { get; set; }

Step 10: Create New Migration

dotnet ef migrations add AddPhoneNumberToUser

Generated Migration

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AddColumn<string>(
        name: "PhoneNumber",
        table: "Users",
        maxLength: 15,
        nullable: true);
}

protected override void Down(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropColumn(
        name: "PhoneNumber",
        table: "Users");
}

Step 11: Update Database Again

dotnet ef database update

✔️ Schema updated
✔️ Existing data preserved


Step 12: Verify Database

Tables:

  • Users

  • __EFMigrationsHistory


Step 13: Rollback a Migration (If Needed)

dotnet ef database update InitialCreate

or

dotnet ef database update 0

Step 14: Remove Last Migration (Not Applied)

dotnet ef migrations remove

📌 Only works if migration not applied


Step 15: Common EF Core Migration Commands

dotnet ef migrations list
dotnet ef migrations script
dotnet ef database update
dotnet ef migrations remove

Step 16: Data Seeding (Optional)

modelBuilder.Entity<User>().HasData(
    new User { Id = 1, Name = "Admin", Email = "admin@test.com", IsActive = true }
);

Then:

dotnet ef migrations add SeedUsers
dotnet ef database update

Real-Time Best Practices

✔️ One migration per feature
✔️ Never edit applied migrations
✔️ Avoid auto-migrate in production
✔️ Review generated SQL
✔️ Always keep migrations in Git


Common Interview Questions

Q: Difference between EnsureCreated() and migrations?
➡️ EnsureCreated() skips migrations – NOT for production

Q: Where migration history stored?
➡️ __EFMigrationsHistory


One-Line Interview Summary

EF Core Code-First migration allows developers to evolve database schema incrementally using C# models while maintaining version control and data safety.


If you want, I can next explain:

  • 🔥 How EF Core tracks model changes internally

  • 🔥 Multiple DbContext migrations

  • 🔥 Zero-downtime production migrations

  • 🔥 Handling breaking changes

  • 🔥 EF Core migration interview Q&A

Just tell me 👍



Tuesday, 14 August 2018

Eager Loading in Entity Framework:

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities. Eager loading is achieved using the Include() method.
In the following example, it gets all the students from the database along with its standards using the Include() method.
LINQ Query Syntax:
using (var context = new SchoolDBEntities())
{
    var stud1 = (from s in context.Students.Include("Standard")
                where s.StudentName == "Bill"
                select s).FirstOrDefault<Student>();
}
LINQ Method Syntax:
using (var ctx = new SchoolDBEntities())
{
    var stud1 = ctx.Students
                   .Include("Standard")
                   .Where(s => s.StudentName == "Bill")
                   .FirstOrDefault<Student>();
}
The above LINQ queries will result in following SQL query:
SELECT TOP (1) 
[Extent1].[StudentID] AS [StudentID], 
[Extent1].[StudentName] AS [StudentName], 
[Extent2].[StandardId] AS [StandardId], 
[Extent2].[StandardName] AS [StandardName], 
[Extent2].[Description] AS [Description]
FROM  [dbo].[Student] AS [Extent1]
LEFT OUTER JOIN [dbo].[Standard] AS [Extent2] ON [Extent1].[StandardId] = [Extent2].[StandardId]
WHERE 'Bill' = [Extent1].[StudentName]

Use Lambda Expression:

You can also use the LINQ lambda expression as a parameter in the Include method. For this, take a reference of System.Data.Entity namespace and use the lambda expression as shown below:
using System;
using System.Data.Entity; 
   
class Program
{
    static void Main(string[] args)
    {
        using (var ctx = new SchoolDBEntities())
        {
            var stud1 = ctx.Students.Include(s => s.Standard)
                            .Where(s => s.StudentName == "Bill")
                            .FirstOrDefault<Student>();
        }
    }
}

Load Multiple Entities:

You can also eagerly load multiple levels of related entities. The following example query eagerly loads the StudentStandard and Teacher entities:
using (var ctx = new SchoolDBEntities())
{
    var stud1 = ctx.Students.Include("Standard.Teachers")
                    .Where(s => s.StudentName == "Bill")
                    .FirstOrDefault<Student>();
}
Or use the lambda expression as below:
using (var ctx = new SchoolDBEntities())
{
    var stud1 = ctx.Students.Include(s => s.Standard.Teachers)
                    .Where(s => s.StudentName == "Bill")
                    .FirstOrDefault<Student>();
}
The above query will execute the following SQL query in the database:
SELECT [Project2].[StudentID] AS [StudentID], 
[Project2].[StudentName] AS [StudentName], 
[Project2].[StandardId] AS [StandardId], 
[Project2].[StandardName] AS [StandardName], 
[Project2].[Description] AS [Description], 
[Project2].[C1] AS [C1], 
[Project2].[TeacherId] AS [TeacherId], 
[Project2].[TeacherName] AS [TeacherName], 
[Project2].[StandardId1] AS [StandardId1]
FROM ( SELECT 
    [Limit1].[StudentID] AS [StudentID], 
    [Limit1].[StudentName] AS [StudentName], 
    [Limit1].[StandardId1] AS [StandardId], 
    [Limit1].[StandardName] AS [StandardName], 
    [Limit1].[Description] AS [Description], 
    [Project1].[TeacherId] AS [TeacherId], 
    [Project1].[TeacherName] AS [TeacherName], 
    [Project1].[StandardId] AS [StandardId1], 
    CASE WHEN ([Project1].[TeacherId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    FROM   (SELECT TOP (1) [Extent1].[StudentID] AS [StudentID], [Extent1].[StudentName] AS [StudentName], [Extent1].[StandardId] AS [StandardId2], [Extent2].[StandardId] AS [StandardId1], [Extent2].[StandardName] AS [StandardName], [Extent2].[Description] AS [Description]
        FROM  [dbo].[Student] AS [Extent1]
        LEFT OUTER JOIN [dbo].[Standard] AS [Extent2] ON [Extent1].[StandardId] = [Extent2].[StandardId]
        WHERE 'updated student' = [Extent1].[StudentName] ) AS [Limit1]
    LEFT OUTER JOIN  (SELECT 
        [Extent3].[TeacherId] AS [TeacherId], 
        [Extent3].[TeacherName] AS [TeacherName], 
        [Extent3].[StandardId] AS [StandardId]
        FROM [dbo].[Teacher] AS [Extent3]
        WHERE [Extent3].[StandardId] IS NOT NULL ) AS [Project1] ON [Limit1].[StandardId2] = [Project1].[StandardId]
)  AS [Project2]
ORDER BY [Project2].[StudentID] ASC, [Project2].[StandardId] ASC, [Project2].[C1] ASC

Sunday, 12 August 2018

Entity Framework Code First Migrations

This walkthrough will provide an overview Code First Migrations in Entity Framework. You can either complete the entire walkthrough or skip to the topic you are interested in. The following topics are covered:
Before we start using migrations we need a project and a Code First model to work with. For this walkthrough we are going to use the canonical Blog and Postmodel.
  • Create a new MigrationsDemo Console application
  • Add the latest version of the EntityFramework NuGet package to the project
    • Tools –> Library Package Manager –> Package Manager Console
    • Run the Install-Package EntityFramework command
  • Add a Model.cs file with the code shown below. This code defines a single Blog class that makes up our domain model and a BlogContext class that is our EF Code First context
    using System.Data.Entity;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity.Infrastructure;

    namespace MigrationsDemo
    {
        public class BlogContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
        }

        public class Blog
        {
            public int BlogId { get; set; }
            public string Name { get; set; }
        }
    }
  • Now that we have a model it’s time to use it to perform data access. Update the Program.cs file with the code shown below.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace MigrationsDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var db = new BlogContext())
                {
                    db.Blogs.Add(new Blog { Name = "Another Blog " });
                    db.SaveChanges();

                    foreach (var blog in db.Blogs)
                    {
                        Console.WriteLine(blog.Name);
                    }
                }

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
    }
  • Run your application and you will see that a MigrationsCodeDemo.BlogContext database is created for you. If SQL Express is installed (included in Visual Studio 2010) then the database is created on your local SQL Express instance (.\SQLEXPRESS). If SQL Express is not installed then Code First will try and use LocalDb ((localdb)\v11.0) - LocalDb is included with Visual Studio 2012. Note: SQL Express will always get precedence if it is installed, even if you are using Visual Studio 2012
    DatabaseLocalDb
    (LocaDb Database)
    DatabaseExpress
    (SQL Express Database)
It’s time to make some more changes to our model.
  • Let’s introduce a Url property to the Blog class.
    public string Url { get; set; }
If you were to run the application again you would get an InvalidOperationException stating The model backing the 'BlogContext' context has changed since the database was created. Consider using Code First Migrations to update the database.
As the exception suggests, it’s time to start using Code First Migrations. The first step is to enable migrations for our context.
  • Run the Enable-Migrations command in Package Manager Console
This command has added a Migrations folder to our project, this new folder contains two files:
  • The Configuration class. This class allows you to configure how Migrations behaves for your context. For this walkthrough we will just use the default configuration. Because there is just a single Code First context in your project, Enable-Migrations has automatically filled in the context type this configuration applies to.
  • An InitialCreate migration. This migration was generated because we already had Code First create a database for us, before we enabled migrations. The code in this scaffolded migration represents the objects that have already been created in the database. In our case that is the Blog table with a BlogId and Namecolumns. The filename includes a timestamp to help with ordering. If the database had not already been created this InitialCreate migration would not have been added to the project. Instead, the first time we call Add-Migration the code to create these tables would be scaffolded to a new migration.

Multiple Models Targeting the Same Database

When using versions prior to EF6, only one Code First model could be used to generate/manage the schema of a database. This is the result of a single __MigrationsHistory table per database with no way to identify which entries belong to which model.
Starting with EF6, the Configuration class includes a ContextKey property. This acts as a unique identifier for each Code First model. A corresponding column in the __MigrationsHistory table allows entries from multiple models to share the table. By default, this property is set to the fully qualified name of your context.
Code First Migrations has two primary commands that you are going to become familiar with.
  • Add-Migration will scaffold the next migration based on changes you have made to your model since the last migration was created
  • Update-Database will apply any pending migrations to the database
We need to scaffold a migration to take care of the new Url property we have added. The Add-Migration command allows us to give these migrations a name, let’s just call ours AddBlogUrl.
  • Run the Add-Migration AddBlogUrl command in Package Manager Console
  • In the Migrations folder we now have a new AddBlogUrl migration. The migration filename is pre-fixed with a timestamp to help with ordering
    namespace MigrationsDemo.Migrations
    {
        using System;
        using System.Data.Entity.Migrations;
        
        public partial class AddBlogUrl : DbMigration
        {
            public override void Up()
            {
                AddColumn("dbo.Blogs", "Url", c => c.String());
            }
            
            public override void Down()
            {
                DropColumn("dbo.Blogs", "Url");
            }
        }
    }
We could now edit or add to this migration but everything looks pretty good. Let’s use Update-Database to apply this migration to the database.
  • Run the Update-Database command in Package Manager Console
  • Code First Migrations will compare the migrations in our Migrations folder with the ones that have been applied to the database. It will see that the AddBlogUrl migration needs to be applied, and run it.
The MigrationsDemo.BlogContext database is now updated to include the Url column in the Blogs table.
So far we’ve generated and run a migration without making any changes. Now let’s look at editing the code that gets generated by default.
  • It’s time to make some more changes to our model, let’s add a new Rating property to the Blog class
    public int Rating { get; set; }
  • Let's also add a new Post class
    public class Post
    {
        public int PostId { get; set; }
        [MaxLength(200)]
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
  • We'll also add a Posts collection to the Blog class to form the other end of the relationship between Blog and Post
    public virtual List<Post> Posts { get; set; }
We'll use the Add-Migration command to let Code First Migrations scaffold its best guess at the migration for us. We’re going to call this migration AddPostClass.
  • Run the Add-Migration AddPostClass command in Package Manager Console.
Code First Migrations did a pretty good job of scaffolding these changes, but there are some things we might want to change:
  1. First up, let’s add a unique index to Posts.Title column (Adding in line 22 & 29 in the code below).
  2. We’re also adding a non-nullable Blogs.Rating column. If there is any existing data in the table it will get assigned the CLR default of the data type for new column (Rating is integer, so that would be 0). But we want to specify a default value of 3 so that existing rows in the Blogs table will start with a decent rating. (You can see the default value specified on line 24 of the code below)
    namespace MigrationsDemo.Migrations
    {
        using System;
        using System.Data.Entity.Migrations;
        
        public partial class AddPostClass : DbMigration
        {
            public override void Up()
            {
                CreateTable(
                    "dbo.Posts",
                    c => new
                        {
                            PostId = c.Int(nullable: false, identity: true),
                            Title = c.String(maxLength: 200),
                            Content = c.String(),
                            BlogId = c.Int(nullable: false),
                        })
                    .PrimaryKey(t => t.PostId)
                    .ForeignKey("dbo.Blogs", t => t.BlogId, cascadeDelete: true)
                    .Index(t => t.BlogId)
                    .Index(p => p.Title, unique: true);

                AddColumn("dbo.Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3));
            }
            
            public override void Down()
            {
                DropIndex("dbo.Posts", new[] { "Title" });
                DropIndex("dbo.Posts", new[] { "BlogId" });
                DropForeignKey("dbo.Posts", "BlogId", "dbo.Blogs");
                DropColumn("dbo.Blogs", "Rating");
                DropTable("dbo.Posts");
            }
        }
    }
Our edited migration is ready to go, so let’s use Update-Database to bring the database up-to-date. This time let’s specify the –Verbose flag so that you can see the SQL that Code First Migrations is running.
  • Run the Update-Database –Verbose command in Package Manager Console.
So far we have looked at migration operations that don’t change or move any data, now let’s look at something that needs to move some data around. There is no native support for data motion yet, but we can run some arbitrary SQL commands at any point in our script.
  • Let’s add a Post.Abstract property to our model. Later, we’re going to pre-populate the Abstract for existing posts using some text from the start of the Content column.
    public string Abstract { get; set; }
We'll use the Add-Migration command to let Code First Migrations scaffold its best guess at the migration for us.
  • Run the Add-Migration AddPostAbstract command in Package Manager Console.
  • The generated migration takes care of the schema changes but we also want to pre-populate the Abstract column using the first 100 characters of content for each post. We can do this by dropping down to SQL and running an UPDATE statement after the column is added. (Adding in line 12 in the code below)
    namespace MigrationsDemo.Migrations
    {
        using System;
        using System.Data.Entity.Migrations;
        
        public partial class AddPostAbstract : DbMigration
        {
            public override void Up()
            {
                AddColumn("dbo.Posts", "Abstract", c => c.String());

                Sql("UPDATE dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL");
            }
            
            public override void Down()
            {
                DropColumn("dbo.Posts", "Abstract");
            }
        }
    }
Our edited migration looks good, so let’s use Update-Database to bring the database up-to-date. We’ll specify the –Verbose flag so that we can see the SQL being run against the database.
  • Run the Update-Database –Verbose command in Package Manager Console.
So far we have always upgraded to the latest migration, but there may be times when you want upgrade/downgrade to a specific migration.
Let’s say we want to migrate our database to the state it was in after running our AddBlogUrl migration. We can use the –TargetMigration switch to downgrade to this migration.
  • Run the Update-Database –TargetMigration: AddBlogUrl command in Package Manager Console.
This command will run the Down script for our AddBlogAbstract and AddPostClass migrations.
If you want to roll all the way back to an empty database then you can use the Update-Database –TargetMigration: $InitialDatabase command.
If another developer wants these changes on their machine they can just sync once we check our changes into source control. Once they have our new migrations they can just run the Update-Database command to have the changes applied locally. However if we want to push these changes out to a test server, and eventually production, we probably want a SQL script we can hand off to our DBA.
  • Run the Update-Database command but this time specify the –Script flag so that changes are written to a script rather than applied. We’ll also specify a source and target migration to generate the script for. We want a script to go from an empty database ($InitialDatabase) to the latest version (migration AddPostAbstract). If you don’t specify a target migration, Migrations will use the latest migration as the target. If you don't specify a source migrations, Migrations will use the current state of the database.
  • Run the Update-Database -Script -SourceMigration: $InitialDatabase -TargetMigration: AddPostAbstract command in Package Manager Console
Code First Migrations will run the migration pipeline but instead of actually applying the changes it will write them out to a .sql file for you. Once the script is generated, it is opened for you in Visual Studio, ready for you to view or save.

Generating Idempotent Scripts (EF6 onwards)

Starting with EF6, if you specify –SourceMigration $InitialDatabase then the generated script will be ‘idempotent’. Idempotent scripts can upgrade a database currently at any version to the latest version (or the specified version if you use –TargetMigration). The generated script includes logic to check the __MigrationsHistory table and only apply changes that haven't been previously applied.
If you are deploying your application you may want it to automatically upgrade the database (by applying any pending migrations) when the application launches. You can do this by registering the MigrateDatabaseToLatestVersion database initializer. A database initializer simply contains some logic that is used to make sure the database is setup correctly. This logic is run the first time the context is used within the application process (AppDomain).
We can update the Program.cs file, as shown below, to set the MigrateDatabaseToLatestVersion initializer for BlogContext before we use the context (Line 14). Note that you also need to add a using statement for the System.Data.Entity namespace (Line 5).
When we create an instance of this initializer we need to specify the context type (BlogContext) and the migrations configuration (Configuration) - the migrations configuration is the class that got added to our Migrations folder when we enabled Migrations.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;
    using MigrationsDemo.Migrations;

    namespace MigrationsDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                Database.SetInitializer(new MigrateDatabaseToLatestVersion<BlogContext, Configuration>());

                using (var db = new BlogContext())
                {
                    db.Blogs.Add(new Blog { Name = "Another Blog " });
                    db.SaveChanges();

                    foreach (var blog in db.Blogs)
                    {
                        Console.WriteLine(blog.Name);
                    }
                }

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
    }
Now whenever our application runs it will first check if the database it is targeting is up-to-date, and apply any pending migrations if it is not.
https://msdn.microsoft.com/en-us/data/jj591621

Recent Post

how to control duplicate order