Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a single migration for a specific model using C# ASP.net MVC 5

I am trying to develop a small application using ASP.NET MVC 5.

I am using Entity Framework with a code first approach.

To get started, I created my first model and then followed the steps below to create the table in the database

  1. I opened the Package Manager Console
  2. I executed Enable-Migrations
  3. I executed Add-Migration InitilizeModel1Table
  4. Finally, to create the table I executed Database-Update

In step 3 created a migration called datetime_InitilizeModel1Table which created the code that will create the table automatically.

In step 4, it applied the create table command and created the table in the database as expected.

Now, I created 3 more models and what I like to do is create a separate migration for each to keep my code separated.

So I thought I would start again at step 2 and so the following

  1. Add-Migration InitilizeModel2Table
  2. Add-Migration InitilizeModel3Table
  3. Add-Migration InitilizeModel4Table
  4. Database-Update

But the command Add-Migration InitilizeModel2Table is creating an empty migration without the code that is needed to create the tables.

Here is an example of one

namespace App.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class InitilizeModel2Table : DbMigration
    {
        public override void Up()
        {

        }

        public override void Down()
        {

        }
    }
}

How can I create a new migration for each model without having to manually write the migration script to create the tables?

like image 560
Junior Avatar asked Oct 11 '25 21:10

Junior


1 Answers

The problem here was that you weren't adding your models to the context, hence EF did not detect the changes.

EF links the state of the model to the migration via the __MigrationHistory table/the migration files themselves. It compares the latest value in __MigrationHistory to the current state of your context, if they are different then a new, non-empty migration will be created when you run Add-Migration X.

Here are a couple of resources describing code-first migrations.

I am by no means an EF expert, so I may be slightly off in the details here.

like image 154
Sven Grosen Avatar answered Oct 15 '25 19:10

Sven Grosen