Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 Create model from existing table

We have to maintain a very old application. There is an old part (all data access is handled with stored procedures) and since my predecessors took over the application, they started to build a new part for the new requirements which uses entity framework 6.

Now the customer has a new requirement that needs access to one of the tables for which there isn't an EF-model yet.

Is there an easy way to automatically create an EF-model from an existing database table? (I only want this one table, not the whole remaining database!) Do you know of any tool that can achieve this or do I have to write it by hand?

Thanks in advance

like image 324
xeraphim Avatar asked Dec 24 '22 18:12

xeraphim


2 Answers

I use EF Power Tools which is a plugin for Visual Studio.

Download here

With the plugin, you can reverse engineer your database in order to create your objects and mappings in your application. Despite the fact that it will save you a lot of time, note that it is not perfect. You might want to review your indexes and relationships as some were missing in my case.

To Reverse engineer your database, it's as simple as this:

The Reverse Engineer Code First command is used to generate the POCO, mapping (configuration), and derived DbContext classes that are based on an existing database.

  • Right click the project and select Entity Framework –> Reverse Engineer Code First.

  • Enter the information about an existing database based on which you want to reverse engineer Code First.

You can check this link from Microsoft for a complete example:

https://msdn.microsoft.com/en-us/data/jj593170.aspx

IMPORTANT: As of Entity Framework 7 (not released yet), only the Code First approach will be used. You might want to consider this before choosing another approach like Model First, for instance. You can read more about: EF7 - What Does “Code First Only” Really Mean

like image 186
Maxime Avatar answered Dec 31 '22 15:12

Maxime


Open the Entity Data Model (edmx) file (edit: or create one if you don't already have one), right click on the design surface in a blank area, and select "Update Model from Database".

Select the proper connection string if prompted, then choose the "Add" tab, and drill down to the tables in your database you want to add and put a check mark by them. Click Finish and you're done.

like image 28
pseudocoder Avatar answered Dec 31 '22 15:12

pseudocoder