Wednesday, June 9, 2010

Entity Framework in NerdDinner

As I explained in a previous post, I decided to implement the NerdDinner tutorial in VS 2010 (.Net 4.0) using the Entity Framework instead. This has been a very enlightening project for me and I am learning some really interesting things along the way. Some old stuff that I just didn't know about and some new 4.0 stuff as well.

In NerdDinner Steps 1 and 2, we create a .NET MVC solution (mine being a 2.0) solution and we create a database (mine being SqlExpress 2008 R2). What I did pretty much parallelled what I saw in the tutorial. NerdDinner Step 3, however, is when we build the model. They of course start out by building a Linq to SQL dbml file. I simply created a Entity Framework (edmx) instead. The dragging and dropping was practically the same. What changed for me was when it came time to use the Entity Framework.

The next thing they have you do is implement a "repository" pattern to encapsulate and abstract some of the code so that the controller does as little (or none, according to good MVC practice) logic as possible. The give you a nice code snippet. That of course, wasn't going to fly with the new entity framework. However, constructing the new code wasn't all that difficult and some stuff didn't even have to change. So here is the code that I implement to meet the requirements of that step.


public class DinnerRepository
{
private NerdDinnerEntities db = new NerdDinnerEntities();
//
// Query Methods
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public IQueryable<Dinner> FindUpcomingDinners()
{
//TODO: 1/1/2009 is a temporary hack so I can see the old data, replace with DateTime.Now before go live!
DateTime now = DateTime.Parse("1/1/2009");
return from dinner in db.Dinners
where dinner.EventDate > now
orderby dinner.EventDate
select dinner;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}
//
// Insert/Delete Methods
public void Add(Dinner dinner)
{
db.Dinners.AddObject(dinner);
}
public void Delete(Dinner dinner)
{
foreach (RSVP r in dinner.RSVPs)
db.RSVPs.DeleteObject(r);
db.Dinners.DeleteObject(dinner);
}
//
// Persistence
public void Save()
{
db.SaveChanges();
}
}

That was pretty easy. The next step, the data validation, was a totally different story. I will explain that in my next post.

No comments:

Post a Comment