Unfold POCO with Entity Framework

Plain Old CLR Object or POCO is a simple object to be used with a complicated, special object framework such as an ORM component. In our context that is POCO with entity framework.

Things to remeber

  1. Deferred/Lazy loading works with POCO entities.
  2. POCO entities are not always needed to be hand-craft. We can use T4 templates for code generation and also entity framework got its own code generation mechanism  that is based on T4.
  3. For complex types with POCO cannot use inheritance with your complex type classes
  4. For complex types with POCO only supported  Complex Type is class. Structs are not supported.
  5. If  we want the Entity Framework to track changes in POCO classes as the changes occur and support lazy loading of the related objects we need to use POCO Proxies.
  6. Change tracking with proxies provides better performance compared to snapshot based change tracking.

Simple workarounds

How to make a POCO deferred enabled?

There are two things you need to do in order to get Deferred Loading support with POCO entities:

√ Declare the property that you would like to load lazily as virtual. These properties can be any collection type that implements ICollection<T>.

√ Enable deferred loading on the context:

context.ContextOptions.DeferredLoadingEnabled = true;

How to enable change tracking proxies

Just follow these rules when defining the POCO

Class must be public, non-abstract or non-sealed.

Class must also implement public virtual getters/setters for all properties that are persisted.

Declare collection based relationship navigation properties as ICollection<T> only. They cannot be a concrete implementation or another interface that derives from ICollection<T>.

The ProxyCreationEnabled option must be set to true.

context.ContextOptions.ProxyCreationEnabled = true;

Define POCO Entities

This example below defines the User, Contact  custom data classes. These classes have been defined to support proxy object creation,

public class User
{
    public virtual Int32 UserID { get; set; }
    public virtual String First_Name { get; set; }
    public virtual String Last_Name { get; set; }
    public virtual String Email { get; set; }
    public virtual String Password { get; set; }
    public virtual DateTime DOB { get; set; }
    // Defines a navigation property to the Contact object.
    public virtual ICollection<Contact> _Contact { get; set; }
}
public class Contact
{
    public virtual Int32 ContactID { get; set; }
    public virtual String Title { get; set; }
    public virtual String Address1 { get; set; }
    public virtual String Address2 { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip_Code { get; set; }
    public virtual Int32 Home_Phone { get; set; }
    public virtual String Office_Phone { get; set; }
}

Leave a comment