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
Enable-Migrations
Add-Migration InitilizeModel1Table
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
Add-Migration InitilizeModel2Table
Add-Migration InitilizeModel3Table
Add-Migration InitilizeModel4Table
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With