Reputation: 6188
I am a HUGE LINQ2SQL Fan. But I use a lot of DataContext in my each function and subsequent use the queries. However, I know there is a better way to do it...
Something like this, maybe?
protected dbMYDataContext FA(dbMYDataContext dt)
{
using (dt = new dbMYDataContext())
{
return dt;
}
}
protected void FunctionA() : FA
{
}
protected void FunctionB() : FA
{
}
So the mantra is that, whenever you want to create a DataContext, inherit or call this function FA. But, I am getting error when I am inheriting it. What seems to be the problem and what is the best practices to reduce the use of DataContext all the time.
Advices?
Upvotes: 1
Views: 146
Reputation: 3772
There are a few things I do when using L2S that vasty improve things alot.
1) Use the using statement as you have shown in your question. This is the correct way of doing things
2) If I am doing a read only query... I set (DataContext).ObjectTrackingEnabled = false. This basically does not track the objects and improves performance a bit. It is set to true by default.
3) If I use a query more than 5 times in a program, I pre-compile the query to make things happen quicker than they would. There are a few caveats with this approach, but using .ToList() at the end seems to fix them all for me :D Follow up link: http://www.codinghorror.com/blog/2010/03/compiled-or-bust.html
It is worth remembering that every time you create a data context, you are getting the latest data. Example, you create a class instance of a data context, another user updates a table, you will not see it (or at least I never do, but it could be the way im doing things. So be warned). :)
Example Code (Not Tested):
protected void MyFunction()
{
using(MyDataContext db = new MyDataContext())
{
// uncomment the following line for read only queries
// db.ObjectTrackingEnabled = false;
// implementation here
}
}
Upvotes: 1