Reputation: 61
I'm working with asp.net mvc3 & Entity Framework5.
My database has been designed with the Code-First.
Entity Code
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class EFDbContext : DbContext
{
public DbSet<User> Users { get; set; }
}
Create DB Option
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFDbContext>());
I use this option, the database has been created.
After the database has been created, I need a Role table was.
So I had to modify the code as follows.
Entity Code
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
}
public class EFDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
}
I use Create DB Option again.
In this case, the existing Users table will be deleted after regeneration.
I would like to be added to the Role table, but leave data in the table Users.
What should I do?
Upvotes: 1
Views: 728
Reputation: 8265
Use Code-First Migrations.
Database.SetInitializer(null);
Then in Package Manager Console
write:
add-migration addedRoles
If you did't enabled migrations before, You must enable it first:
enable-migrations
and last:
update-database
Complete guid: http://msdn.microsoft.com/en-US/data/jj591621
Edit
If you want the database to be upgraded automatically whenever you run the application, you can use MigrateDatabaseToLatestVersion
initializer:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<EFDbContext, Configuration>());
Upvotes: 1
Reputation: 48230
Learn how migrations work.
http://msdn.microsoft.com/en-us/data/jj591621.aspx
They have another initializer, MigrateDatabaseToLatestVersion
. In contrast to the one you use, this one will automatically upgrade your database to latest version without recreating the whole database.
Upvotes: 0