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?



Anonymous Anonymous said...

Queryable.Where{T}() returns IQueryable{T}, which is builidng a query expression that isn't evaluated immediately. It will be evaluated (and the exception will be thrown) when the Count() method is called on it.

The exception will be related to ef being disposed.

8/22/2013 5:37 PM  
Blogger Ann said...

Nicely done, Mike!

12/30/2013 9:37 AM  

Post a Comment

<< Home