Sunday, July 21, 2013

Bad Idea Challenge #3

This looks like okay code, doesn’t it?

   public IEnumerable<County> GetCounties(int stateId)
{
using (var ef = new TopologyEntities())
{
return ef.Counties.Where(c => c.stateId == stateId);
}
}

After all, it’s using the using pattern with the IDisposable-implementing EF data context.   Isn’t that what you’re supposed to do?

But:  the following code will throw an error. 


       var counties = GetCounties(10);
var count = counties.Count();

Do you see why?

(For bonus points) Which line of this code will throw the exception? Why?


Labels: