POCO in ADO.NET Entity Framework 4

January 18th, 2011 Comments off

ADO.NET Entity Framework means many things to many people.  At it’s core, however, it allows for Object Relational Mapping (ORM) by providing a layer of abstraction between relational databases and Object Oriented domain objects.

The first version of Entity Framework was introduced with .NET Framework 3.5 SP1 and Visual Studio 2008 SP1.  While the intention was great, most of everyone that I know, including my own self who have ever tried using EFv1 for anything except trivial data access have developed a love-and-hate relationship with it.  The first version looked great at first, but turned out to be an immature product at best with severe restrictions as well as quite a few bugs.

With .NET 4 Microsoft released a new version of Entity Framework that has addressed many of the issues and made it a much more stable technology.  Amongst other things, Microsoft heard developer community at large and provided POCO support in EFv4.

POCO Support – At Last!

The biggest problem with EFv1 was that the domain classes had to be tightly integrated with EF.  Essentially these classes were generated from entity models and developers had no control over code generation.  This limitation didn’t fly very well with most developers, since we like to keep our domain classes generic enough to where we can easily migrate them to any underlying data access technology.  This is especially true since the data access technologies tend to change every so often.

In EFv4 Microsoft has gone to great lengths to support Plain Old CLR Objects (POCO), which is just a fancy name for simple .NET classes with properties that can be used as Data Transfer Objects (DTO) or simply Domain Objects.

POCO classes can be handwritten and easily hooked in to EFv4.  Better yet, EFv4 allows us to generate these classes based on our entity models.  Also we have complete control over code generation since EFv4 uses T4 templates.  Speaking of T4 templates, they can also be used to generate ObjectContext classes for our entity models.

Lazy Loading, Explicit Loading, and Eager Loading

In EFv1 the only way to automatically load related entities was using eager loading.  Essentially eager loading is a LINQ technique that allows loading related entities in one shot using the Include method on the LINQ query.

EFv4 allows for lazy loading on POCO’s.  The only requirement for this added functionality is that navigation properties on POCO’s be marked as virtual and LazyLoadingEnabled property of ObjectContextOptions be set to true.  The way EFv4 does this is very cool.  Essentially it generates dynamic proxies overriding the virtual properties on POCO’s and uses those proxies instead of the POCO classes at runtime.

In addition to eager and lazy loading, EFv4 allows explicit loading of related entities.  Explicit loading allows us to explicitly load related entities on demand whenever the need arises.  Using explicit loading is as easy as calling the LoadProperty method of the ObjectContext using  the parent entity as well as the navigation property name as parameters.

Change Tracking

EFv4 supports two different types of change tracking which are as follows:

Snapshot Change Tracking.  Using this kind of change tracking is more efficient in most cases but it might require a few additional lines of code.  When using snapshot change tracking (default behavior in EFv4), the developer must make explicit call to ObjectContext’s DetectChanges method in order for the EF change tracker to notice any data that has been changed on the entity since it was first retrieved.  Also calling the SaveChanges method of the context automatically detects any changes to entities involved.

Real-time Change Tracking.  Using real-time change tracking the tracker keeps track of all data changes to entities in real-time.  For real-time change tracking to work for POCO’s, all properties of POCO’s should be marked as virtual.  Also any navigation properties should have return types of ICollection<T>.  Once these two conditions are met, EFv4 automatically generates dynamic proxies and uses them instead of the POCO’s and tracks changes made to data contained within those entities in real time.

Design Techniques

EFv4 allows a couple of different design techniques that ought to satisfy most situations.

Model First.  For new projects where that database design is not already set in stone or is non-existent, model-first approach is more natural to most developers and makes a lot of sense.  What this entails is that the developer creates an entity model using the Entity Model Designer for the domain objects involved.  This model can be easily changed during the design phase or the early development stages.  Once the architect/developer is happy with the entity design, he/she can use EFv4 to generate the data model using EFv4’s Data Definition Language (DDL) generation capabilities.  Not only that this is a more natural way of designing data access and domain model for a given solution, it’s more agile in that the model can easily be modified using a GUI tool.  Also as long as the underlying database is supported by EFv4, the developer need not worry about the exact syntax of the DDL as it can automatically be generated.  Once again the generation of DDL can be influenced using T4 templates.

Database First.  This technique is more suitable for when a project involves an existing database.  In such cases EF can easily generate domain models based on database schema.  This design technique is not new to EFv4 as it has been available since the first version of EF and this is probably what most of us are most familiar with.

Code Only.  EFv4 introduced another design technique which requires no models to be created.  Essentially there are only code classes and EF infers the model from them.  Entire database including all required tables can be generated by EF at run-time.

There’s a lot more to EFv4.  What I have covered in this article only addresses a bit of POCO support in EFv4 since that has been the number 1 request of the development community since EFv1 was released.

ASP.NET GridView And Conditional Images

September 14th, 2006 Comments off

Depending upon a value in the data source, we can conditionally display images in GridView columns. For example, the following TemplateField declaration conditionally displays approved.gif or unapproved.gif based on IsApproved flag in the DataSet that the GridView is bound to:

<asp :Image ID="ApprovalImage" runat="server" ImageUrl="" />

ADO.NET Calculated Columns

September 9th, 2006 Comments off

ADO.NET offers the capability to add calculated columns in typed DataSets and use the Expression property of the those columns to specify the formulae for calculations. What I did not realize is that you must use the Fill method of the adapter instead of the Get method for calculated columns to properly populate. For example:

using (MyTableAdapter adapter = new MyTableAdapter())
    MyTypedDataSet.MyTable dt =
          new MyTypedDataSet.MyTable(true);
    adapter.FillData(dt, beginDate, endDate);

Get Table Schema Programatically

August 18th, 2006 Comments off

In order to retreive table schema programatically, we can use the GetSchemaTable method of the DataReader as follows:

using (OleDbConnection cn = new OleDbConnection())
    OleDbCommand cmd;
    DataTable schemaTable;
    OleDbDataReader reader;

    cn.ConnectionString = @"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Northwind;Data Source=(local);";

    cmd = new OleDbCommand("Employees", cn);
    cmd.CommandType = CommandType.TableDirect;

    using (reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo))
        schemaTable = reader.GetSchemaTable();

        foreach (DataRow row in schemaTable.Rows)
            foreach (DataColumn col in schemaTable.Columns)
                Console.WriteLine(col.ColumnName + " = " + row[col].ToString());