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: bad idea challenge
2 Comments:
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.
Nicely done, Mike!
Post a Comment
<< Home