Geeks With Blogs
Dane Morgridge Programmer, Geek, ASPInsider
A blog about code and data access

I was giving an Entity Framework talk in Harrisburg, PA at the Central Penn Code Camp earlier today and afterwards I was talking with one of the developers that attended my session. He was a little hesitant to use Entity Framework because he didn't want to use it solely as his data layer.  I explained that you don't have to use it directly as your data layer but could add another layer of abstraction.  This is actually how I use Entity Framework almost exclusively.  In short, how I do this is I build a set of classes that do all the interaction with the Entity Framework context.  I use these classes to wrap my Entity Framework calls so that I don't use my data context directly within say a mvc controller.  Below is a sample of how I do this:


   1: public class ContactAdministration
   2: {
   3:     public List<Person> GetAllPeople()
   4:     {
   5:         using (ContactEntitiesContainer db = new ContactEntitiesContainer())
   6:         {
   7:             return db.Person.ToList<Person>();
   8:         }
   9:     }
  11:     public Person GetPerson(int personId)
  12:     {
  13:         using (ContactEntitiesContainer db = new ContactEntitiesContainer())
  14:         {
  15:             return db.Person.Where(p => p.PersonId == personId).FirstOrDefault<Person>();
  16:         }
  17:     }
  18: }


This is a basic example of how I would implement a data layer class that wraps the Entity Framework.  Then when I need to access data from with in my application I can simply so some calls like:


   1: ContactAdministration contactAdmin = new ContactAdministration();
   3: List<Person> people = contactAdmin.GetAllPeople();
   5: Person p = contactAdmin.GetPerson(1);


This method has quite a few advantages.  First off, it allows for more persistence ignorance in your data layer (especially if you are using EF4 POCO classes) and it also give you a greater separation of concerns. It also gives you simple code reuse since you will likely call some of the methods in more than once place in your application.

So basically what we have it a method where you can use Entity Framework as your data access technology, but not necessarily as your direct data layer.  It requires you to write a little more code up front, but less down the road and makes the code more maintainable.

Posted on Saturday, December 5, 2009 11:05 PM | Back to top

Copyright © Dane Morgridge | Powered by: