1

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?

0

2 Answers 2

1

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>()); 
Sign up to request clarification or add additional context in comments.

5 Comments

I believe for migrations to be applied from code (not manually), you have to use the MigrateDatabaseToLatestVersion initializer.
Thank you. Migration is successful you provided.
However, I have some questions.
'Update-database-Verbose' I don't know whether this command to perform some action.This command, what does it mean?
It's update-database -verbose (there is a space after 'database'). It tells the EF: "Show me the SQL statements you are executing on my database"
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.