EF Business Classes in ASP.NET Apps - Don't pass that query around!

Sunday, August 31 2008

Here's a little sidebar from my book that I think is pretty important.

Return Results, not Queries from the Business classes

While you can get away with binding a query when working directly in the code behind of an ASP.NET page, remember that the query’s job is to be executed and return results. Query execution requires an ObjectContext. If you returned the query itself from a business class, it will be detached from the context as soon as the business object is disposed (the business object, in turn, disposes the context) and you are very likely to get an exception when the query attempts to execute. If it is bound directly to a data binding control, that execution won't occur until the control is being rendered at which time the business object could be long gone. So in the business class, be sure to return results, not queries, and you wont' have to worry about how the methods are being used.

An additional benefit is that by executing the query and forcing the results to be iterated through (using foreach, First, ToList, etc), when the iteration is complete, the EntityConnection and its database connection are disposed. Therefore you won’t have to think twice about the database connection, which is an unmanaged resource.