Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate POCO classes in different project to the project with Entity Framework model

I'm trying to use the Repository Pattern with EF4 using VS2010.

To this end I am using POCO code generation by right clicking on the entity model designer and clicking Add code generation item. I then select the POCO template and get my classes.

What I would like to be able to do is have my solution structured into separate projects for Entity (POCO) classes and another project for the entity model and repository code.

This means that my MVC project could use the POCO classes for strongly typed views etc and not have to know about the repository or have to have a reference to it.

To plug it all together I will have another separate project with interfaces and use IoC.

Sounds good in my head I just don't know how to generate the classes into their own project! I can copy them and then change the namespaces on them but I wanted to avoid manual work whenever I change the schema in the db and want to update my model.

Thanks

like image 227
Max Avatar asked Mar 17 '10 18:03

Max


People also ask

How do I generate POCO in Entity Framework?

Now, we must create properties (Context and Entities), so for this, we need to create POCOs classes. Now, double-click on Modal1. edmx and right-click on the designer surface and click on the code generation Items. A screen will open from where you need to select ADO.NET POCO Entity Generator and click Add.

What is POCO entity in Entity Framework?

POCO Entities (Plain Old CLR Object) A POCO entity is a class that doesn't depend on any framework-specific base class. It is like any other normal . NET CLR class, which is why it is called "Plain Old CLR Objects". POCO entities are supported in both EF 6 and EF Core.

What is Entity Framework reverse POCO generator?

The Reverse POCO Generator is a T4 template packaged as a Visual Studio extension allowing you to scaffold Entity Framework elements based on an existing database. It generates code such as DbContexts, entities, unit testable Fakes, stored procedures, and views just to name a few.


1 Answers

Actually the T4 templates in EF 4.0 were designed with this scenario in mind :)

There are 2 templates:

  • One for the Entities themselves (i.e. ModelName.tt)
  • One for the ObjectContext (i.e. ModelName.Context.tt)

You should put the ModelName.tt file in you POCO project, and just change the template to point to the EDMX file in the persistence aware project.

Sounds weird I know: There is now a dependency, but it is at T4 generation time, not at compile time! And that should be okay? Because the resulting POCO assembly is still completely persistence ignorant.

See steps 5 & 6 of this: http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx for more.

Hope this helps

Alex

like image 110
Alex James Avatar answered Oct 01 '22 11:10

Alex James