I
ll continue with this
tutorial to show how to upgrade or downgrade the database schema.
Suppose
we need to add one more field ManagerAddress in our existing
Managers tables, To do this we need to use one feature called
Migrations . It allows us
to have an ordered set of steps that describe how to upgrade (and
downgrade) our database schema.
Each
of these steps, known as a migration, contains some code that
describes the changes to be applied.
The
two new file get created under Migrations folder :
Configuration.cs
:
It contains the setting that Migrations will use for migrating
ManagingContext.
<timestamp>_InitialCreate.cs –
This is your first migration, it represents the changes that have
already been applied to the database to take it from being an empty
database to one that includes the Manager and Employee tables.
Now
we will add one more field ManagerAddress
to the Manager Model.
public
class
Manager
{
public
int
ManagerId { get;
set; }
public
String
ManagerName { get;
set; }
public
String
ManagerAddress { get;
set; }
public
virtual
List<Employee>
Employees { get;
set; }
}
The Add-Migration command checks for changes since your last migration and scaffolds a new migration with any changes that are found. We need to give migrations a name; in this case we are calling the migration ‘AddManagerAddress
’.
The scaffolded code is saying that we need to add a ManagerAddress column, that can hold string data, to the dbo.Managers table. If needed, we could edit the scaffolded code but that’s not required in this case.
namespace
CreateNewDatabase.Migrations
{
using
System;
using
System.Data.Entity.Migrations;
public
partial
class
AddManagerAddress
: DbMigration
{
public
override
void Up()
{
AddColumn("dbo.Managers",
"ManagerAddress",
c => c.String());
}
public
override
void Down()
{
DropColumn("dbo.Managers",
"ManagerAddress");
}
}
}
The
new ManagerColumn column is now added to the Managers table in the
database: