Saturday, March 10, 2012

Updating Database in EntityFramework "Code-First"

Today i have used EntityFramework "CodeFirst" for the first time.
I think it is a very interesting approach but the VisualStudio Integration could be more intuitive.

I have integrated it in an ASP.NET MVC Application. This task is described perfectly in a short video from Scott Hanselman.

What is missing in the video and took me some time, is the update of the database structure if the model has been changed (Well it is a MVC-Video, not an EF-Video). If you are using "Database First", you can simply update your .edmx file. In the "Code First" scenario we have to do some manual stuff. 

After you have created the application in the video (or your own EF-Based Application), run it and create some entries in the database. Than add an additional Property to one of your Model-Classes. For udpating the database structure run the following in the Package Manager Console.

PM> Enable-Migrations
PM> Add-Migration AddAppointmentSubject
PM> Update-Database

The "AddAppointmentSubject" can be named by your own. Here the structure is <task><class><property>.

There seems to be some issues/changes with the Version 5 (PreRelease) of EntityFramework. This stuff is running great on 4.3.1.

More details about updating the Model (e.g. new classes) you can find here.

Kind Regards,
Markus