Wednesday, 22 September 2010

Using POCO in Entity Framework 4

The entity classes that are generated from Entity Framework inherit from System.Data.Objects.DataClasses.EntityObject, Entity Framework version 1 was blamed for lake of support for testability. The current Entity Framework V4 now supports POCO classes. This post shows how you can do that. Please note that you need Visual Studio 2010, the express edition will do.

Database Schema
This example uses an simple Event Booking system with the following three tables.

Creating the Entity Framework model
The first step is to create a cenceptual model. In the visual studio, add one item "ADO.NET Entity Data Model", follow the wizard and select all tables, the end result is as follows. Please note, that the EventBooking table is not in the model, instead, you can see two navigation properties. The Entity Framework is very smart to work out the relationship.

Turn off code generation from Entity Model
By default, the Entity Framework will generate code for you, but the default one is inherited from EntityObject and this is not what we want. So we are going to turn off the automatic code generation. Firstly click anywhere in the design view of Entity Model, then from the Properties window, change the Code Generation Strategy to "None", this will turn off code generation because we are going to use our POCO classes.

Installing POCO Entity Generator Extension
Next, you need to install one extension, go to Tools -> Extension, then go to Online Gallery, and install the ADO.NET C# POCO Entity Generator.

Generating POCO Entities
Now we are ready to generate our POCO entities. Add a new item to the project, a new entry "ADO.NET POCO Entity Generator" will be available.

Select that and name it "", it will add two files "" and "", the "tt" extension is the Microsoft T4 template.

Next open the "" file and replace "$edmxInputFile$" with "EventModel.edmx" and save it, it will automatically generate entity POCO classes. Do the same with "". Now you can start using the POCO classes.

In the next post, I want to talk about generic Repository and Unit of Work pattern by using Entity Framework and POCO.

1 comment:

Asava Samuel said...

This is even better than Entity Framework: