Entity Framework - Generating Classes
Solution 1:
1) 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.
2) 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)
3) 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:
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:
- 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:
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