Linq to SQL is great. I love it because it adds a simple abstraction layer that can greatly speed up building a data access layer.
If not used properly, LINQ to SQL can also create performance issues. Here are my general LINQ to SQL guidelines when I work in projects:
Use the “using” statement when working with a context
This is mostly a general C# programming guideline but there have been several times when I see programmers missing this step. Here is more information from MSDN.
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources.
A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.
Here is an example:
using (NorthwindDataContext context = new NorthwindDataContext())
{
//do stuff here
}
Compiled queries
To query something with LINQ to SQL there are several “startup” procedures. This procedures are not too bad when queries are not used too often. If the same query is done several times, its heavy and it is the core of the product then it is VERY important to make it a compiled query.
I will not go into too many details about this because there are several posts about the subject:
- LINQ to SQL Compiled Queries
- High Performance LINQ To SQL – Compiled Queries – O/R Mappers – Ecommerce Websites
Use multiple tiny contexts instead of big bulky ones
Contexts are meant to keep track of the objects in the database. By having small contexts with a single purpose then the burden of tracking is lessen and therefore there is less memory consumption.
Do not keep track of object changes in the database unless its needed
There are two good ways to improve the performance of queries that do not involve concurrency issues:
- Optimistic concurrency = off
- Object tracking = off
For object tracking, is super easy to turn off:
context.ObjectTrackingEnabled = false;
Combine Queries and custom expressions
Combining queries is a good idea when working with databases, just grab what you need and aggregate the data into a POCO model or anonymous type. Finally, if extreme fine control is needed, there is always custom expressions.