Unfold POCO with Entity Framework





5.00/5 (3 votes)
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 Remember
- Deferred/Lazy loading works with POCO entities.
- 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.
- For complex types with POCO cannot use inheritance with your complex type classes
- For complex types with POCO only supported Complex Type is class. Structs are not supported.
- 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.
- 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:
context.ContextOptions.DeferredLoadingEnabled = true;
- 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:
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; }
}