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.
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.):
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.
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:
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