Separating POCO and Context in EF 4.0

16. August 2010

I found that I like the streamlined process of working with Entity Framework. The auto generation of domain class is nice when dealing with Existing databases. I dislike having to put domain classes in Infrastructure or putting data base context in Core.

Using the POCO Entities T4 templates you can separate these.

Download here

Add a new Entity Data Model and Generate from the data base.

image

Then right click the background of the model and add a generated code item.

image

Select the POCO Objects

image 

This will create Two .tt files. One is the POCO Classes and one is the Context. We are going to use the onion architecture for this example. We want to move the context to infrastructure so that our model and POCO classes and model are in core.

image

and

image

To separate the context from the Domain we will need to edit the context template. You do not want to edit the classes generated because this will just get wiped out.

image

image

The edit we have to make is to simply add the namespace of the Domain objects to the using statements, and the path of the EDMX file to the input. I am still hunting a way to keep from hard coding a absolute path to the EDMX but until then this will have to work.

 

Enjoy.

C#, Data Access, Design Patterns, Entity Framework