Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Migration when Generate database from model in Entity Framework Model First

I have an existing model and initially generated the database from this model and had populated the existing tables with some data. Now I've added a new table to the model. Is there a way to update the database from the new model without losing all the data in the existing tables? Thanks.

like image 812
user282807 Avatar asked Nov 19 '10 03:11

user282807


People also ask

How do you do migration in db first approach?

To do this, Suppose that you have the following DbContext that EF Db first created for you: public class MyDbContext : DbContext { public MyDbContext() : base("Name=DefaultConnection") { } // DbSets ... } change that to the following to start using code first and all magic tools of it (migration, etc.):

How do I transfer data in Entity Framework?

If you want to use the framework for changes like this, you should separate Database changes from Data changes. Create a migration for just the Database changes, and execute. Then create a new migration (the Up() and Down() methods will be empty). You can now instantiate your DatabaseContext and there will be no error.


1 Answers

EF's default database generation workflow creates a full script that will recreate your database every time you select Generate Database from Model... so if you execute it in your DB you will lose all your data. However, if you just create a new Entity and did not change the existing ones, then you can still generate database from your Model but then take that script and only run the part that creates the new table for your new entity.

Another way would be to install Entity Designer Database Generation Power Pack from Microsoft which didn't make it to be in EF4.0 release. After you install it, change your database generation workflow to Generate Migration TSQL when you generate Database from your Model:

alt text

like image 152
Morteza Manavi Avatar answered Sep 23 '22 06:09

Morteza Manavi