Update: CTP3 is now available. This sample project below works fine with the new version but I have written a new post and sample project with some enhancements.
In my initial post I tried out the “Code First” 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 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
[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
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.
