Entity Framework 4 : POCO support 1 (via ObjectContext)

POCO stands for “Plain Old CLR Objects”. POCO classes are basically classes which we generally write with all the public properties (e.g. Customer, Order).  Now, EF4, by default generates all the entities for us (we will see this in this article) and we dont have to write those classes. Just becuase EF does this, in order to distinguish “OUR” classes or the “Classes written by us” from the generated classes, we call those “OUR” classes as POCO classes.

There are basically 2 ways you can make use of POCO support in EF4:-

A) Via ObjectContext
B) Via T4 Templates  (this will be covered here)

 

A) Via ObjectContext :-

This is done the following way:-

i) Generate the model using the wizard.
ii) Turn off the code-generation (because you want to write code yourself).
iii) Create your POCO classes, Address and Contact in this case and dont have them inherited from EntityObject.
iv) Create your own ObjectContext class.
v) Use your ObjectContext class to use POCO classes.

 

i) Generate the model using the wizard:-

Create a console application and follow the below steps:-

Step 1 :-
image

 Step 2 :-
image

Step 3 :-
image

When you click the “Finish” button above, you should see an EDMX file and a code-behind file added to your solution. Double-clicking the edmx file shows the following:-
image

Code-behind file contains the following :-
image

As you see the classes “Contact” and “Address” inherit from EntityObject. there would be times when you dont want your entities to be separated in their own class library and dont want them to get inherited from the EntityObject class. So you (very conventionally) create your own classes named Address and Contacts with the stardard public properties. When objects of those “YOUR” classes are called Plain Old CLR Objects or POCO.

ii) Turn off the code-generation (because you want to write code yourself):-

Select the EDMX file in the solution explorer and go to its property window (press F4). Delete the value for the “Custom Tool” in the properties window.

image image

when you have deleted the custom tool value, notice that the code-behind for the EDMX file is gone and you are on your own to create entities which we will see in the next step.

iii) Create your POCO classes, Address and Contact in this case and dont have them inherited from EntityObject.
Create a class library and create the following classes :-

The Contact class
public class Contact
    {
        public int ContactID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        public DateTime AddDate { get; set; }
        public DateTime ModifiedDate { get; set; }
        public ICollection<Address> Addresses { get; set; }

    }

The Address class
public class Address
    {
        public int addressID { get; set; }
        public string Street1 { get; set; }
        public string Street2 { get; set; }
        public string City { get; set; }
        public string StateProvince { get; set; }
        public string CountryRegion { get; set; }
        public string PostalCode { get; set; }
        public string AddressType { get; set; }
        public DateTime ModifiedDate { get; set; }

        public int ContactID { get; set; }
        public Contact Contact { get; set; }
    }

iv) Create your own ObjectContext class:-

public class POCOObjectContext : ObjectContext
{
       private ObjectSet<Contact> contacts;
       private ObjectSet<Address> addresses;
       public POCOObjectContext()
           : base("name=AddressBook2Entities", "AddressBook2Entities")
       {
           contacts = CreateObjectSet<Contact>();
           addresses = CreateObjectSet<Address>();
       }
       public ObjectSet<Address> Addresses
       {
           get { return addresses; }
       }
       public ObjectSet<Contact> Contacts
       {
           get { return contacts; }
       }

}

Notice the constructer getting used takes two parameters:-

image

For the first parameter (“name”) we are passing is the name of the connection string in config file. This connection string got added when we generated the model from the database.
For the second parameter, we are passing the name of the container. On the properties window of the edmx file, look for the value for “Entity Container Name”.

image

Using the application :-

Use the classes in the main method of the console application. Below is just printing all the contacts from the “Contact” table.

class Program
    {
        static void Main(string[] args)
        {
            using (POCOObjectContext context = new POCOObjectContext())
            {
                List<Contact> contacts = context.Contacts.ToList();
                foreach (var item in contacts)
                {
                    Console.WriteLine(item.FirstName.Trim() +" "+ item.LastName.Trim());
                }
                Console.ReadLine();
            }
        }
    }

The output:-
image

Summary:-

So, we saw that ObjectContext or your class (inheriting from the ObjectContext) is smart. Although our entity class is not inheriting from the EntityObject, ObjectContext  can look at them and let us work with the them just like we could have with the generated code. The advantage here (with POCOs) is our entities are clean and do not have any dependency on Entity Framework which enables better organized code and gives us flexibility for unit testing etc.

Advertisements
  1. #1 by Beeth on November 2, 2011 - 7:20 pm

    Ashish , your article really rocks..
    Excellently written.. nice screen shots….
    Picture perfect….

  2. #2 by ashishmgupta on November 2, 2011 - 8:00 pm

    Beeth, Thanks. I’m glad It helped.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Random Thoughts

The World as I see it

Simple Programmer

Making The Complex Simple

Ionic Solutions

Random thoughts on software construction, design patterns and optimization.

Long (Way) Off

A tragic's view from the cricket hinterlands

%d bloggers like this: