Udostępnij za pośrednictwem


Walkthrough: POCO Template for the Entity Framework

It is now recommended to use the DbContext template described in this blog post. It will generate simpler POCO entities and a context class derived from DbContext which provides a simpler API.

The POCO Template can be used to generate persistence ignorant entity types from an Entity Data Model. The goal of this walkthrough is to demonstrate a basic scenario of its use with Entity Framework. 

Requirements

  1. Any edition of Visual Studio 2010 post-Beta 2. 
  2. Entity Framework POCO Template for C#, available here.
  3. A local SQL Server 2008 Express instance has to be installed as SQLEXPRESS. Otherwise, it might be necessary to make changes to the connection string in the configuration file or to regenerate the database from the included SQL script.
  4. Download and extract the initial solution attached to this post.

Note: While the following walkthrough uses C#, all the concepts described here apply to the Visual Basic version of the template which is available here.

1. Setting up the project

The solution includes a project named POCOTemplateWalkthrough that is a Console Application. To facilitate us focusing on how to use the POCO Template, the solution already contains the following files:

  • Blogging.edmx: a simple Entity Data Model for a blogging application.
  • Blogging.mdf: a SQL Server database for the blogging model.
  • Blogging.edmx.sql: SQL Server script that can be used to regenerate the database if needed.
  • Program.cs: the initial Program class created for console applications.
  • App.Config: an application configuration file containing the connection string for the blogging database.

Normally, when you start a new project using Entity Framework you can import a model from an existing database. In version 4.0, you can now create a database starting from the model. To learn more about the Model-First feature, see this blog post.

2. Understanding the Blogging model

If you open the “Blogging.edmx” file, this is what you will see:

image

Five simple classes are used to model a blogging application: Blog represents an actual blog. A Person can act as the owner of a blog, but also as the author of a Post or a Comment, which both inherit from the abstract class Entry. A Blog can have multiple Posts, and in turn, each Post can have several Comments.

Notice that we are using foreign key associations in this model: Blog has both Owner and OwnerID properties. It is important to note, however, that exposing foreign key in entities is not a requisite for Entity Framework or the POCO Template.

By default, a model created with the Entity Data Model Designer produces entity classes based on System.Data.Objects.DataClasses.EntityObject, which provides basic services to entities, such as change notification, identity and relationship management. Special attributes are used to decorate classes and properties, so that Entity Framework can at runtime relate each class and property with the corresponding property in the model. In order to see the kind of code that is generated by default, expand the Blogging.edmx associated files by clicking on the arrowhead close to it, and then open the file Blogging.Designer.cs:

image

POCO stands for Plain-Old CLR Objects. POCO support in Entity Framework 4.0 means that these EntityObject-based types can be replaced with much simpler classes. POCO entity types are not required to inherit from any particular class and do not need attributes to map to the homologous elements in the model. Instead, types and properties in the objects and in the model are associated at runtime simply based on their names. 

For an overview of POCO entities support you can read parts 1, 2 and 3 of this blog series on POCO and Entity Framework, and also this post on the use of patterns with Entity Framework 4.0.

3. Adding the POCO template

One of the advantages of POCO entities is that they are simple. So in general, it is very easy to write them by hand. However, when you have an Entity Data Model as the starting point and want your entity classes to be POCO, the POCO Template can provide a good jumpstart by generating POCO classes that correspond to the model instead of the default EntityObject classes.

In order to do this, you can right-click on an empty area of the “Blogging.edmx” canvas and select “Add Code Generation Item...”

image

This will bring up the Add New Item dialog, in which you can choose which Template you wish to use. The POCO Template can normally be found under the Visual C# Items or the Visual Basic Items category.

image

On this screen select “ADO.NET POCO Entity Generator” and type “Blogging.tt” as the name of the new item. Then click on the “Add” button.

Note: A Security Warning dialog will appear each time a T4 generates code from a template in your machine:

image

Normally, T4 template files generate code when they are added to a project or when they are saved. If you have downloaded and installed the template form a trusted source, you can click “OK”.

4. Understanding how the POCO Template works

Once you have added the POCO template, your project will look like this:

image

When you choose the POCO Template two T4 template files are added to your project. In this case one is called “Blogging.Context.tt” and the other is called “Blogging.tt”. T4 stands for Text Template Transformation Toolkit, and is a template engine that ships with Visual Studio. The Entity Framework POCO Template leverages T4 to allow you to customize code generation.

The “Blogging.tt” file is responsible for generating a file for each EntityType and ComplexType in the “Blogging.edmx” model. For instance, the POCO version of the Blog class looks like this:

image

“Blogging.tt” also generates a file called “Blogging.cs”, which contains a FixupCollection<T> class used by the POCO classes to keep the opposite ends of a relationships in sync.

For example in the model we’ve been using when you set a Comment's Author to a particular person the FixupCollection<T> class ensures that the Person's Comments collection will contain the Comment too.

The second template (“Blogging.Context.tt”) produces a strongly typed ObjectContext for the “Blogging.edmx” model. You use this strongly typed ObjectContext to interact with your database.

Note that each time you edit and save any T4 template the dependent files are regenerated, so you shouldn’t edit the generated files directly, or your changes will be lost. If you wish to modify the generated code, you can modify one or both of these templates.

Note: Why two templates?

The primary goal of the POCO template is to produce persistence ignorant entity classes.

However, the strongly typed ObjectContext derives from ObjectContext, which is an Entity Framework class. So this template must live in a project with a reference to the Entity Framework.

By splitting the template into two, one part that generates the Entity Types and Complex Types and one that generates a strongly typed context, it makes it possible not only to have Entities and ComplexType that are persistence ignorant but further to put those classes in an assembly / project that has no persistence aware code in it at all.

The next few steps show how to do this.

5. Moving entity types to a separate project

To continue, add a new Class Library project to the solution called Entities.

image

You can remove the class1.cs file created by default in the new project.

Now, in the POCOTemplateWalkthrough project, add a project reference to the Entities Project:

image

Next, move the “Blogging.tt” file into the Entities project. To do that, you can simply drag & drop the file into the Entities project in the Solution Explorer window, while you hold the Shift key at the same time.

The POCO Template T4 template files need to be able to read metadata from the EDM model in order to generate the right code. Since we have moved the template, the relative location of the Model has changed, therefore we need to fix the template so its link back to the model is correct again. To do this you can modify a line close to the top of the template from from:

string inputFile = @ “Blogging.edmx” ;

To:

string inputFile = @ “..\POCOTemplateWalkthrough\Blogging.edmx”;

This is simply a relative path from the template’s new location to the Blogging.edmx file in the other project.

Once you’ve done this Save the template, and this will regenerate the POCO entity classes. You can check that the contents of the file “Blogging.cs” under “Blogging.tt” has the right contents to verify that the path entered above is correct:

image

Also, notice the Entities project has no reference to the System.Data.Entity (aka the Entity Framework), and is completely persistence ignorant.

7. Change “ Blogging.Context.tt” namespaces to match “Entities”

The classes in the Entities project are now in the Entities” namespace rather than the POCOTemplateWalkthrough” namespace, so you need to modify the namespace used by the context template. Otherwise the compiler won’t find the entity types and the solution won’t compile. You can do this by setting the value of the “Custom Tool Namespace” property to “Entities” in the property browser of the template item.

image

Once you do this, save the template file again (i.e. by pressing Ctrl+S) and you should be able to compile the solution without errors.

 

 

8. Sanity check: adding and querying for data in the Blogging database

Now that we are done producing POCO classes it is time to verify that we can add some data to the database and get it back again using our POCO classes and the Entity Framework.

First, add this using statement at the top of the “Program.cs” file:

using Entities;

Then modify the Main() method by adding the following two blocks of code:

using (var ctx = new BloggingContainer())
{   
    var person = new Person();   
    person.EmailAddress = "billg@microsoft.com";
    person.Firstname = "Bill";   
    person.Surname = "Gates";   
    ctx.People.AddObject(person);   
    ctx.SaveChanges();
    Console.WriteLine("Saved {0}", person.Firstname);
}
using (var ctx = new BloggingContainer())
{
    var person = ctx.People.First();   
    Console.WriteLine("Found {0}", person.Firstname);
}

9. Final step: compile and run the code

After following all the steps described before, you should be able to compile and run the code and see the following screen:

image

Customizing classes and templates

The entity type, complex type and ObjectContext classes generated by the POCO Template are all partial classes. Therefore, it is often possible to extend the behavior of entities by just adding a partial class containing additional code to the project.

In other cases it might be better to modify the templates themselves to generate different code. Indeed, the whole point of a template-based solution is that you can decide the behavior you want only once, and then obtain the desired output from different models by applying a modified template.

Modifying the T4 Template files consists of modifying a text file, but it is beyond the scope of this basic walkthrough. Customization of T4 templates for entity code generation is described in this post.

Creating your own T4 template is not covered in this walkthrough either. You can expect future posts to explore more in depth this area. In the meanwhile, it is worth mentioning that T4 provides a mechanism by which you can write common utilities that you share across templates, in something called include files. The POCO template uses an include file called EF.Utility.CS.ttinclude. This include provides a number of utility feature that make writing T4 templates for Entity Framework easier, among others:

  • Multiple output file support. By default each TT file produces just one output file, this multiple file support makes it possible to create a single class per file, which has several advantages.
  • Functions to produce Safe Identifiers. It is possible in the EDM to have identifiers, like an Entity Type name, that are reserved in the target CLR language.
  • Functions to control the visibility (public / protected etc) of properties etc.
  • Functions to interact with the Entity Framework metadata

Known issues in this version

  1. The POCO Template does not work with ASP.NET WebSite projects: A bug in multiple output file support prevents the POCO Template from working on WebSite projects. A fix will be available in a future update. In the meanwhile, you can place the template in a separate class library project and add a reference to the class library from the WebSite.
  2. Running a query with Include and MergeOption equal to NoTracking may cause an exception: There is a problem in the interaction between the implementation of relationships fixup code in classes generated by the POCO template and the change tracking POCO Proxies enabled by the POCO Template.  We are currently investigating this issue.
  3. Detach can cause nullable foreign keys properties to be nulled: The implementation of relationship fixup cannot distinguish the reason an entity is being removed from an object graph. When Detach is applied to an entity that is related to others through foreign key associations, fixup logic will react to references being nulled and elements being removed form collections and will set the corresponding FK properties to null. We are currently investigating this issue.
  4. The AssociationChanged event can be raised twice: The AssociationChanged event is raised twice with CollectionChangeAction.Add when fixup occurs in the model such that a collection is modified. We are currently investigating this issue.
  5. The fixup logic will load all related entities if Lazy Loading is enabled. The template keeps relationships consistent even if the related objects haven’t been loaded in the context. You would need to disable Lazy Loading when using the POCO template to avoid this.

Diego Vega and Alex James 
Entity Framework Team

POCOTemplateWalkthrough.zip

Comments

  • Anonymous
    January 25, 2010
    Hello, Can you please attach the source code for this walkthrough ?

  • Anonymous
    January 25, 2010
    The initial solution is missing !

  • Anonymous
    January 26, 2010
    I just installed the POCO Template for VS2010 (and restarted VS), but after creating my DataModel (from a database), I cannot find the option of POCO generation after clicking 'Add Code generation item'; only got 'EntityObject generator' and 'Self-Tracking Entity generator', no POCO in the list... Am I missing something?

  • Anonymous
    January 26, 2010
    David, I had this problem too (I installed from VS Gallery). In the Extension Manager, there was a link at the bottom to allow extensions for all users (or something similar). Might be the same problem ...

  • Anonymous
    January 26, 2010
    Thanks Stephen, the trick worked.

  • Anonymous
    January 26, 2010
    For # David Do not run VS 2010 as Administrator and you'll see it.

  • Anonymous
    January 27, 2010
    Where is the Blogging.edmx and its solution?

  • Anonymous
    January 28, 2010
    Abhijeet, for some reason the solution attached to the post wasn't showing. This has been fixed now.

  • Anonymous
    January 28, 2010
    The comment has been removed

  • Anonymous
    January 28, 2010
    We also recommend enabling "Automatically check for updates to installed extensions" setting to see future updates to the POCO template when they become available. The update will be visible as the total number of updates available for your installed extensions next to the "Updates" tab in the Extension Manager dialog.

  • Anonymous
    February 08, 2010
    I tried to download the 'Entity Framework POCO Template for Visual Studio Beta 2 for C#' but when the page loads I get the message 'This item is not yet published.'

  • Anonymous
    February 09, 2010
    Yes, this template isn't there anymore :( Does this has something to do with VS2010 RC1? Do I need it now to download this template?

  • Anonymous
    February 19, 2010
    Tobias, Phil and others, a new version of the template that is compatible with Visual Studio 2010 RC is now available. Please find the announcement here: http://blogs.msdn.com/adonet/archive/2010/02/18/entity-framework-poco-template-updated-for-visual-studio-2010-release-candidate.aspx. Hope this helps, Diego

  • Anonymous
    February 23, 2010
    Hi Diego, thanks for the updates. The only one that seems to be available is the 'ADO.NET C# POCO Entity Generator'.  The 'ADO.NET C# Web Site POCO Entity Generator' is not available.  I can download it and install from the link but it doesn't show in VS 2010 either in the Installed Templates or Online Templates. Thanks, Phil

  • Anonymous
    March 12, 2010
    Is this a one-way thing? Once the Entities have been moved to the other project, they don't seem to be re-generated when changes are made to the model...correct? Or am I missing something?

  • Anonymous
    April 02, 2010
    The comment has been removed

  • Anonymous
    April 03, 2010
    As a followup to my last post: The .edmx file that ships with the sample doesn't exactly match up to the database that ships with the sampee.  If you delete that .edmx and regenerate it,  then you can subsequently do update from database without compile problems. If you move the .tt file over to a new project, then everytime you refresh the model from the database,  you will need to copy the newly generated .tt file over to your new project.  In addition, you will need to fix the references in the context.tt as well. Sort of painful but not unworkable.

  • Anonymous
    April 13, 2010
    Hi, Can't download the template:

  • In the Windows Gallery download I get a "ICAP Protocol Error" response (which I believe it's a local proxy server issue (?))
  • From the VS 2010 (ver 10.0.30319.1 RTMRel) IDE online templates I receive an "Internal Server Error" response. Any other alternative to download it? Thanks, Andrey
  • Anonymous
    April 18, 2010
    Hello, After used this templated I am not able to have navigation properties loaded properly. Is it a problem in my side or a known limitation? Thanks, Marcio Cunha

  • Anonymous
    April 18, 2010
    When trying to build the proejct I get the errors like this: Error 4 The type or namespace ame 'FixupCollection' could not be found (are you missing a using directive or an assembly reference?)

  • Anonymous
    April 26, 2010
    Folks, Thanks for this example. I can run through the code without problem, but when I check the MDF there is no records inserted into the person table. Any ideas on what is wrong here?

  • Anonymous
    May 04, 2010
    Any idea when it will support HIERARCHYID in Sql Server 2008?

  • Anonymous
    May 11, 2010
    I'm not seeing any data in the MDF as well.  Anyone know what's going on there? thanks

  • Anonymous
    May 11, 2010
    got it, the mdf file gets copied to the bin directory and written to there.  The mdf in the root does not get updated.

  • Anonymous
    May 12, 2010
    Hi, I'm testing this poco structure and cannot update an object after they are detached.

  1. Get Context in a using statment
  2. Get Entity Works (Person)
  3. Change Person.Firstname
  4. Dispose of the context by ending the using clause.
  5. I now have a person entity that is no longer attched to the context (context doesn't exist)
  6. Create a new context in a using clause
  7. Attach the person entity to context.People
  8. dbe.SaveChanges(). Looking in the database shows that the entity did not get updated. Am I missing something? Any help would be appriciated. Rgds Hitesh
  • Anonymous
    May 12, 2010
    Hi Sorry made a mistake in the previous post. Here is the Save code  public void Save(Person toSave)        {           using( DAL.DBEntities dbe = new DAL.DBEntities()){            dbe.People.Attach(toSave);            dbe.SaveChanges();           }        } Once again thnx in advance.

  • Anonymous
    May 13, 2010
    Hi, I manged to get something working but am not sure if this is the best / correct way. What I did was to seperate the generation of the Linq Query:- private IQueryable<Person> GetById(DAL.DBEntities dbe, Guid Id)        {            return (from x in dbe.People                    where x.PersonId == Id                    select x);        } This allows me to use the same query in differnt routines And then in the Save operation :- public int Save(Person toSave)        {           using( DAL.DBEntities dbe = new DAL.DBEntities()){               if (toSave.PersonId == Guid.Empty)               {                   //New Person                   dbe.People.AddObject(toSave);               }               else               {                   //Exisiting Person                   var p = GetById(dbe, toSave.PersonId).SingleOrDefault();                   dbe.People.ApplyCurrentValues(toSave);                   toSave.Updated = DateTime.Now;               }            int i = dbe.SaveChanges();            return i;           }        } Rgds Hitesh

  • Anonymous
    June 04, 2010
    This article was fine until Step 5. I think it is necessary to add a project reference for Entities to the Model project in order to compile, which is not mentioned. Also, why is the console app not in a separate project from the Model? This project structure creates a circular dependency if you try to access the context from outside the Model project. Also there are namespace typos in the sample code download. Overall, a poor article.

  • Anonymous
    June 11, 2010
    Hello, I've downloaded your sample.  Thanks for the great concise walkthrough.  I have 1 question though.  What if I have a UI layer? You have 2 layers, the model layer, the POCO layer.  I would like to add a UI layer.  Is this possible?  Any help would be greatly appreciated. Thanks, Todd

  • Anonymous
    July 26, 2010
    I get the following error when using Entity Framework POCO Template with ASMX & WCF web service: Cannot serialize member Dal.POCO.Site.Roles of type System.Collections.Generic.ICollection`1[[Dal.POCO.Role, Dal.POCO, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] because it is an interface. Am I missing some configuration to make this work?

  • Anonymous
    August 04, 2010
    I've tried this walkthrough as well as the EFCodeFirstWithDatabase one. Both projects fail at this point:    public class Northwind : DbContext    {        public DbSet<Product> Products { get; set; }        public DbSet<Category> Categories { get; set; }    } DbContext and DbSet are undefined, and I don't see any mention of them. Was there an earlier project this is based on?

  • Anonymous
    August 08, 2010
    blogs.msdn.com/.../walkthrough-poco-template-for-the-entity-framework.aspx

  • Anonymous
    August 09, 2010
    The problem with this approach is that now my context object (the Container class) is in the "wrong" namespace. I want the Entities namespace to only have POCOs in it, but due to step 7, that namespace contains the data context as well, even though the code for it is actually in the other assembly.  It's generally advisable to avoid having assembly/namespace mismatches, I'd think. Since the T4 template is added to the solution and solution-specific changes to it are fine, instead of changing the Custom Tool Namespace in step 7 I just added a using statement in the .Context.tt .  I personally think that's a wiser plan.

  • Anonymous
    August 20, 2010
    Hello, what about concurrency dealing with POCO objects generated from this template? Being pure POCO, whena having a Timestamp field is there still the need for the tracking of  the ObjectStateManager.ChangeObjectState(..) calls and check? Thanks, D.

  • Anonymous
    August 26, 2010
    I've found what might be a bug. I want to import Stored Procs which don't return a resultset. The context code generator is failing to output them due to the following code fragment.            if (edmFunction.ReturnParameter == null)            {                continue;            } (skips to the next function) Not sure why it needs to be there. If I copy the function code over myself which lies in the model designer.cs file it seems to be OK. Am getting around it by returning a scalar result in my procs, which I'd rather not do. e.g. SELECT 1 AS ResultCode Cheers.

  • Anonymous
    August 29, 2010
    Hi ! How can I validate the generated POCOs? Can anybody tell me where I must implement the validation logic? I want to use the IDataErrorInfo-Interface. Thanks for help, MCT

  • Anonymous
    September 08, 2010
    The comment has been removed

  • Anonymous
    September 24, 2010
    No problems following the process on my own project and I'm able to compile. However as I've seen 2-3 other posts on this also go unanswered I'm going to ask the same question again... Why does the system not generate new Entities, etc once the Model.tt is removed and placed into the business layer? The Intent here is to have persistent ignorant objects which is achieved, however any future maintenance does not seem possible with this structure...

  • Anonymous
    October 15, 2010
    to DJacobus,i have the same issue, but i managed to regenerate the new entities by running CUSTOM TOOL on the tt's, not a perfect solution but it works!!!!!!!!!!!!!!!!

  • Anonymous
    October 30, 2010
    Thanks for the post. Can you let me know what to do if i dont want the BOs generated by this template but have to use the manually written business objects even though i still want to keep thecontext.tt file. will just exclude the model1.tt ( the one which includes the business objects) ?

  • Anonymous
    November 11, 2010

  1. Or you will Conduct.
  2. Ciean no. Name Lee Hanil ok korean.
  3. zip:545-873. Address: Jeollanamdo GwangyangySi Gwangyuon 798-7. phone:82-010-8272-9896.
  4. ALL of my Money korea Exchomge BANK account. property. South korea.KEB:620-190745-891. Lee Hanil. This one to deposit in the account.
  • Anonymous
    December 20, 2010
    Very informative. The part of this article where you explain the relative path to the edmx file was especially helpful. Thank you.

  • Anonymous
    December 30, 2010
    Hi, I was looking at the blog on POCO with EF4 (blogs.msdn.com/.../walkthrough-poco-template-for-the-entity-framework.aspx). I am facing a issue with the update operation on the POCO object. Here is what i am doing. I have created a POCO object for the table Student{ID, FirstName, LastName, Semester, IsActive}. Now I want to update ONLY the Semester column. Way 1: Student newStud = new Student(){ID=10, Semester = "Six"}; using(StudentEntities context = new StudentEntities()) { //reqyuire extra round trip to the DB to get the original item var originalItem = context.Students.First(s => s.ID == newStud.ID); //this will update ALL the fields with the values from the newStud. In this case it will update FirstName , LastName to null, as we have not set them to the newStud object. context.Students.Attach(originalItem); context.Students.ApplyCurrentValues(newStud); context.SaveChanges(); } Problem with this way is,

  1. It require you to perform one extra round trip to the DB (extra select statement) to get the original Item.
  2. This method updates other fields such as FirstName, LastName with NULL values if we dont set them properly for the newStud object. This is quite dangerous. Also this method update ALL the fields and not only the updated ones. Run SQL profiler and see the UPDATE statement. Way 2: //Assume a scenario where i want to update the IsActive flag to FALSE and i want to set the LastName to NULL for the student with ID = 10 Student newStud = new Student(){ID=10, IsActive=false, LastName=null}; using(StudentEntities context = new StudentEntities()) { var originalItem = new Student(){ID=newStud.ID); //This dont need extra DB call to get the original Item context.Students.Attach(originalItem); //This will dont update the IsActive to False and LastName to Null. context.Students.ApplyCurrentValues(newStud); context.SaveChanges(); } Problem with this aproach,
  3. This method dont update the ISActive and LastName field with FALSE and NULL. I can understand this is by design, since when we create a object all the fields get set with the default values, for boolean False and for strings NULL. so the context.SaveChanges() fails to identify what values to update, as it assumes that no property is set. Good this about this approach is it updates ONLY the specific fields and not all the fields. Run SQL profiler. I can understand this is by design, but first of all why do Microsoft crerate wrong design. They should provide some alternative gto set Boolean fields to False, string fields to NULL with the second aproach. Please let me know.
  • Anonymous
    January 18, 2011
    This worked well for me. Although I didn't follow the instructions exactly, I was able (with a bit of playing around) to add POCO support for my own entity model and write / read data from my database. One of the more interesting concepts I learned from this article is its possible to retrospectively add POCO support to an existing project that has an entity connection. Nice!

  • Anonymous
    January 30, 2011
    I was just wondering.  In the provided Blogging database the Person table has the ID field set not to be a autonum.  This obviously means that one will need to compile your own ID for each person.  Would it not be better to change the ID field to an autonum and have the ID automatically increment for each person. I made the change, but found that an error was returned reading "... IDENTITY_INSERT set to off".  Don't know how to resolve this issue. Regards.

  • Anonymous
    February 28, 2011
    I found and fixed a bug in the template related to calling stored procs as function imports with no return type.  Not sure where else to report it, but the fix is documented over at StackOverflow: stackoverflow.com/.../5147861

  • Anonymous
    March 11, 2011
    I have downloaded, installed and restarted VS 2010. when I create a POCO generator and the follow error happens: Error 1 Running transformation: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: Unable to locate file   at Microsoft.VisualStudio.TextTemplating.VSHost.TextTemplatingService.ResolvePath(String path)   at Microsoft.VisualStudio.TextTemplating.VSHost.TextTemplatingService.ResolvePath(String path)   --- End of inner exception stack trace ---   at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)   at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)   at Microsoft.VisualStudio.TextTemplatingA9DB2432A51EA8D42A615FBEB2ECB4E5.GeneratedTextTransformation.DynamicHost.ResolvePath(String path)   at Microsoft.VisualStudio.TextTemplatingA9DB2432A51EA8D42A615FBEB2ECB4E5.GeneratedTextTransformation.MetadataLoader.TryCreateEdmItemCollection(String sourcePath, String[] referenceSchemas, EdmItemCollection& edmItemCollection)   at Microsoft.VisualStudio.TextTemplatingA9DB2432A51EA8D42A615FBEB2ECB4E5.GeneratedTextTransformation.MetadataLoader.CreateEdmItemCollection(String sourcePath, String[] referenceSchemas)   at Microsoft.VisualStudio.TextTemplatingA9DB2432A51EA8D42A615FBEB2ECB4E5.GeneratedTextTransformation.TransformText()   at Microsoft.VisualStudio.TextTemplating.TransformationRunner.RunTransformation(TemplateProcessingSession session, String source, ITextTemplatingEngineHost host, String& result) 1 1

  • Anonymous
    March 14, 2011
    Hi, i have the same error that Bruno. Can be because is a webSite Project?

  • Anonymous
    March 23, 2011
    Just wanted to echo what grant.bowering said on page 3. Changing the custom tool namespace on the DbContext template puts the data context into the wrong namespace. Instead add a using to the template to get your POCO project included and then this process works great. I'm using it with the new Oracle support and it's going very well so far.

  • Anonymous
    March 29, 2011
    @Bruno and MatiasGuacharaca:  The following steps may resolve your issue.  Open the .edmx file, right click on the diagram you'll see come up, and select "Add Code Generation Item."  This fixed the issue for me.

  • Anonymous
    April 06, 2011
    For anyone interested in using the POCO generator with a 3.5 project, note that in the Context.tt template, you need to replace ObjectSet with ObjectQuery and CreateObjectSet with CreateQuery, since ObjectSet was introduced with 4.0. I also found that I had to add a reference to the WindowsBase assembly in order for the ObservableCollection object to be found. Otherwise, no problems - thanks for creating the template! -Dan

  • Anonymous
    April 21, 2011
    Just tried it and it worked, however if you re run the test, it fails with a database exception. Seems the Foreign key on person table is not being handled, and the app keeps trying to register the person with the same ID.

  • Anonymous
    April 22, 2011
    Hi, The method of adding the POCO template and separating is fine, with the single point that its better to add a using Entities, to the Context.tt file. However if you want to run the test more than once, it fails as the Identity is not handled. Simply changing the ID to an identity in the designer did not work, and EF started complaining Error 3034: Two entities with different keys are mapped to the same row, this presumably being that two model entities inherit from the single row. So rather than an exercise in POCO classes, it became an exercise in EF and multiple inheritance! Anyhow couldn't get it to work, so had to delete entire model, and recreate from database, then reapply the POCO template to the new model which then picked up the Identity fine and could rerun the test without it complaining of primary key violations.

  • Anonymous
    May 02, 2011
    Any update on the "known issues" #3 - Detach can cause nullable foreign keys properties to be nulled?

  • Anonymous
    July 12, 2011
    The t4 templates do not appear to work now that I have installed the June 2011 CTP.  In my context class file I just get a message that "No EntityContainer exists in the model, so no code was generated".  Do I need to modify my .tt file in anyway now that I have install the June 2011 CTP?  I made sure that I had already installed Visual Studio SP1 before hand. Many Thanks, Lee.

  • Anonymous
    May 05, 2012
    Is there a way to completely avoid edmx generation or make it ignorable? I want to have only code-first DbContext and POCOs, so I can make database initialization and all the rest not included in the designer should be added in the partial classes of the context or the entities. Please vote for the suggestion here: http://goo.gl/dfWis

  • Anonymous
    May 06, 2012
    @Shimmy - If you are using Code First there is no need to use the Designer (in fact you can't). If you want to generate Code First classes from an existing database then check out the EF Power Tools - blogs.msdn.com/.../ef-power-tools-beta-2-available.aspx

  • Anonymous
    May 10, 2012
    @Rowan miller. No, I want to use code-first but I do want to use a designer in order to generate the code-first classes. I'm gonna use a database initializer as well. Here is a simple solution I found. Whatever the generator doesn't do, I add using data-annotations and fluent API in the context and entities' partial classes, check it out: blogs.microsoft.co.il/.../entity-framework-code-first-designer-with-database-initialization-in-few-simple-steps.aspx

  • Anonymous
    May 11, 2012
    @Shimmy - Do you mean that you want a tool that will generate the classes so that you don't have to hand type them? If so, then the EF Power Tools is what you are after - blogs.msdn.com/.../ef-power-tools-beta-2-available.aspx. Code First is all about editing code rather than making changes in a designer. Folks often get DbContext and Code First confused... you can use DbContext with the designer, but Code First means no EDMX file. Instead of changing boxes and lines you edit code.

  • Anonymous
    February 22, 2013
    This tutorial tells us to download the source code, but gives no link to download it.

  • Anonymous
    February 23, 2013
    @Sam: the download is called POCOTemplateWalkthrough.zip. It should appear at the very bottom of the post,above the comments. In any case, the POCO template is now considered obsolete, and the recommendation is to use the DbContext template (which generates simpler POCO classes) instead. Find a link to a post describing the DbContext template at the beginning of this post.

  • Anonymous
    April 24, 2014
    Alternatively, you can download my project on Codeplex. I have a working example that you can copy. entityinterfacegenerator.codeplex.com

  • Anonymous
    October 24, 2014
    Just curious. I like the project and my complements on it. But what does this give you that EF doesn't? In my case I build my database, then I generate the classes using EF by adding a edmx file. When I look into this, I get a fancy diagram, which I almost never use cause I can just change my real database and update the diagram. But I am usually interested in the auto generated code, and EF does generate pocos which can be seen easily enough by clicking on your dbcontext and pressing F12. They are all partial classes so I can extend them as needed. Now if I use this program, and I would like to, what would I gain? Will it update the poco's automatically when my model changes. Is there somewhere I can click to easily do this like EF does. If I just have a second set of partial classes, with the same names as EF classes, now I have 2 places to worry about if I need to change anything. I used EF power tools and for this reason I stopped. Perhaps I am missing something and I would like to know. I do understand it takes a good bit of work to do something like this, so EF must be lacking something if there is a demand by experienced developers for this kind of tool. Obviously I am not all that experienced or I would not need to ask. So I hope you can help. Thanks again for the program, your work, and any help you can provide.

  • Anonymous
    October 24, 2014
    @jack: The POCO template is very old. You can think about it as a precursor of what EF 6.x does nowadays with the "DbContext template", i.e. while the POCO template generated a context class based on ObjectContext, which is one of our old APIs, the DbContext template generates a context class that is based on DbContext. The DbContext template also generates "Plain Old CLR Objects" for your entity and complex types, only they are simpler than the ones that POCO template used to generate. Sorry if finding this post was confusing to you. We put a comment in red color under the title of blog posts if the information they describe isn't current, but I guess that can be missed.

  • Anonymous
    December 26, 2014
    If you want generate pure POCO classes - use this tool: ufo.codeplex.com/.../latest