I have a member class that returned IQueryable from a data context
public static IQueryable<TB_Country> GetCountriesQ()
{
IQueryable<TB_Country> country;
Bn_Master_DataDataContext db = new Bn_Master_DataDataContext();
country = db.TB_Countries
.OrderBy(o => o.CountryName);
return country;
}
As you can see I don’t delete the data context after usage. Because if I delete it, the code that call this method cannot use the IQueryable (perhaps because of deferred execution?). How to force immediate execution to this method? So I can dispose the data context..
Thank you 😀
The example given by Codeka is correct, and I would advice writing your code with this when the method is called by the presentation layer. However, disposing
DataContextclasses is a bit tricky, so I like to add something about this.The domain objects generated by LINQ to SQL (in your case the
TB_Countriesclass) often contain a reference to theDataContextclass. This internal reference is needed for lazy loading. When you access for instance list of referenced objects (say for instance:TB_Country.States) LINQ to SQL will query the database for you. This will also happen with lazy loaded columns.When you dispose the
DataContext, you prevent it from being used again. Therefore, when you return a set of objects as you’ve done in your example, it is impossible to call theStatesproperty on aTB_Countryinstance, because it will throw aObjectDisposedException.This does not mean that you shouldn’t dispose the
DataContext, because I believe you should. How you should solve this depends a bit on the architecture you choose, but IMO you basically got two options:Option 1. Supply a
DataContextto theGetCountriesQmethod.You normally want to do this when your method is an internal method in your business layer and it is part of a bigger (business) transaction. When you supply a
DataContextfrom the outside, it is created outside of the scope of the method and it shouldn’t dispose it. You can dispose it at a higher layer. In that situation your method basically looks like this:Option 2. Don’t return any domain objects from the
GetCountriesQmethod.This solution is useful when the method is a public in your business layer and will be called by the presentation layer. You can wrap the data in a specially crafted object (a DTO) that contains only data and no hidden references to the
DataContext. This way you have full control over the communication with the database and you can dispose theDataContextas you should. I’ve written more about his on SO here. In that situation your method basically looks like this:As you will read here there are some smart things you can do that make using DTOs less painful.
I hope this helps.