Pages

Thursday, January 10, 2013

Model- to Code-First with Entity Framework

This applies to Entity Framework versions 4.1 and above. In brief, the steps are liste below.
This is the simplest way, provided by the EF team: 
"Open the .edmx file in the Entity Designer.

Right-click an empty area on the Entity Designer surface and point to Add Code Generation Item.

In the Add New Item dialog, select Online Templates and type DBContext in the Search Online Templates text box.

Select the appropriate version for your template (5.0, if you want to target the Entity Framework 5.0).

Click OK."

* Generate .edmx model from existing database (instructions)
* Install "EF 5.x DbContext Fluent Generator for C#" (link)
* Add "EF 5.x DbContext Fluent Generator" item to the project
* Edit the template files, replacing $edmxInputFile$ with the name of the model generated earlier (i.e. model.edmx) in all three template files.
* [The generation will happen automatically when templates are saved.]
* Delete .tt files related to the .edmx model and leave the diagram file, if desired.

Additional information:
How to: Create a New .edmx File (link)
Entity Framework 5 - How to generate POCO classes from existing database (link)

No comments: