Entity Framework - Generating Classes
C#Entity FrameworkC# Problem Overview
I have an existing database. I was hoping there was a way to generate class files from this database. However, I seem to see a lot of generating the database from the class files.
Is there a way to generate class files from an existing database using the Entity Framework? If so how? Can someone point me to a tutorial?
C# Solutions
Solution 1 - C#
- First you need to generate
EDMX
model using your database. To do that you should add new item to your project:
- Select
ADO.NET Entity Data Model
from the Templates list. - On the Choose Model Contents page, select the Generate from Database option and click Next.
- Choose your database.
- On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need.
So now you have Model1.edmx
file in your project.
- To generate classes using your model:
- Open your
EDMX
model designer. - On the design surface Right Click –> Add Code Generation Item…
- Select Online templates.
- Select
EF 4.x DbContext Generator for C#
. - Click ‘Add’.
Notice that two items are added to your project:
Model1.tt
(This template generates very simple POCO classes for each entity in your model)Model1.Context.tt
(This template generates a derived DbContext to use for querying and persisting data)
-
Read/Write Data example:
var dbContext = new YourModelClass(); //class derived from DbContext var contacts = from c in dbContext.Contacts select c; //read data contacts.FirstOrDefault().FirstName = "Alex"; //edit data dbContext.SaveChanges(); //save data to DB
Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.
Solution 2 - C#
I found very nice solution. Microsoft released a beta version of Entity Framework Power Tools: Entity Framework Power Tools Beta 2
There you can generate POCO classes, derived DbContext and Code First mapping for an existing database in some clicks. It is very nice!
After installation some context menu options would be added to your Visual Studio.
Right-click on a C# project. Choose Entity Framework-> Reverse Engineer Code First (Generates POCO classes, derived DbContext and Code First mapping for an existing database):
Then choose your database and click OK. That's all! It is very easy.
Solution 3 - C#
- Open the EDMX model
- Right click -> Update Model from Browser -> Stored Procedure -> Select your stored procedure -> Finish
- See the Model Browser popping up next to Solution Explorer.
- Go to Function Imports -> Right click on your Stored Procedure -> Add Function Import
- Select the Entities under Return a Collection of -> Select your Entity name from the drop down
- Build your Solution.
Solution 4 - C#
EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html