This article uses older version of EF
Visit basic tutorials section if you are using Entity Framework 5.0 with VS2012.
If you want to use POCO entities instead of default EntityObject derived entities then you can generate POCO entity classes from Textual Transformation Template Toolkit aka T4 Template. You don’t have to write it manually.
To create POCO entities, first of all we have to disable default code generation which generates Context and Entities code in Model1.designer.cs. To disable default code generation, right click on Model1.edmx and select properties and then remove the value of ‘Custom Tool’ property value ‘EntityModelCodeGenerator’.
After removing Custom Tool property value, you can see that Model1.designer.cs file do not exists. So this means that we have to write Context and Entities on our own. Don’t worry; we will generate POCO Entities and context in just few steps.
So now let’s create POCO entities using T4 template. Right click on designer surface and select "Add Code Generation Item.."
This will open ‘Add New Item’ popup. Select ‘ADO.NET POCO Entity Generator’ and click ‘Add’.
Click "OK" if it display messagebox. This will add 2 files Model1.tt and Model1.Context.tt.
Model1.Context.tt is a context template file and Model1.tt is entities template file. You can modify this template file if you want to create your own template. Model1.Context.cs file has a context class and .cs files under Model1.tt are entity classes.
You can see that entity classes have all properties marked as "Virtual". So this means that these entities fulfill the requirements of POCO Proxy entities along with other requirements. These entities can be treated as POCO entities or POCO Proxy entities. By default it will be treated as POCO Proxy entities but you can disable the proxy creation by setting "ObjectContext.ContextOptions.ProxyCreationEnabled = false". So that context will not create Proxy for the POCO entities.
So this way you can create POCO/POCO Proxy classes and context class from T4 template.
- Replace ObjectSet<> to IObjectSet<> if you want to write unit test for context.
- If you can’t see ‘ADO.NET POCO Entity Generator’ then you have to install it from NuGet package library by right clicking on project and selecting "Add Library Package Reference..".