Entity Framework – Code Only Looking Good (part 2)

In my initial post I tried out the “Code Only” methodology of Entity Framework. Taking the code only experiment a step further, I built a sample WCF service that queries and updates a table for holidays. You can download the project if you want to take a look. You can also browse and download the project via github.

The console application “HolidayService.GenerateSchema” is very similar to the first post. It’s used to create the initial sqlexpress database and put in some initial test data. I did try out a simple configuration using some best practices from this site.

The WCF service has two methods.


    [ServiceContract]
    public interface IHolidays
    {
        [OperationContract]
        IList<Holiday> GetHolidayDetails(DateTime startDate, DateTime endDate);

        [OperationContract]
        int AddHolidayDetails(DateTime date, string name);
    }

In the HolidayService I created a HolidayManager class for CRUD operations. It uses a GlobalContext class to build an EF HolidayModel ObjectContext. For example, this is what that GetHolidays method looks like in the manager.


  using (holidayContext)
  {
     var holidayQueryResult = (from h in holidayContext.Holidays
     where h.HolidayDate < endDate & h.HolidayDate > startDate select h);

     foreach (var item in holidayQueryResult)
     {
          holidays.Add(item);
     }
  }

In the GlobalContext class, is where my simple project started to feel some pain. It doesn’t feel right to be using a concrete version of the HolidayModel in the ContextBuilder which returns the ObjectContext. I also don’t like that the sql connection string and connection are all in this class. In another post, I’ll use some of the suggestions below to try to make this area more flexible.


var builder = new ContextBuilder<HolidayModel>();
builder.Configurations.Add(new HolidayConfiguration());
var connStr = ConfigurationManager.ConnectionStrings["UserDBConn"].ConnectionString;
var connection = new SqlConnection(connStr);
return builder.Create(connection);

Since this is a small project I didn’t go any further to clean up the GlobalContext class. I’ll leave that for next time I look into code only. Below are some links which investigate managing ObjectContext, dynamic models, and using EF in a business architecture.

  1. Managing Entity Framework ObjectContext
  2. how to create a dynamic model using code only
  3. Daniel Wertheim – EfEntityStore
  4. Putting Entity framework 4 to use in a business architecture
  5. Repository implementation – Entity Framework 4.0: a fresh start
You can leave a response, or trackback from your own site.

Leave a Reply

Disclaimer The information expressed in this blog are my own personal opinions.