A2Zmenu.Com
Blog
Tutorials
Online Exam
Ask Question
Utility
Fun @ Work
Wiki
Contact Us
About Us
Loading
Home
Blogs
AJAX
ASP.NET
BI
CSharp
JavaScript
LINQ
Miscellaneous
MVC
SQL
SharePoint
Silverlight
WCF
Tutorials
HTML5
ASP.NET 4.0
CSharp
SharePoint
SQL Function
Online Exam
ASP.NET
LINQ
Silverlight
SQL
JavaScript
SharePoint
Forum
Utility
Fun @ Work
Appraisal
Funny Images
Funny Puzzle
Miscellaneous
Motivating Stories
Life Vs Work
Wiki
Contact Us
AJAX
ASP.NET
BI
CSharp
JavaScript
LINQ
Miscellaneous
MVC
SQL
SharePoint
Silverlight
WCF
Test Your Skill
Q. Out of Boxing and Unboxing which one is implicit?
Boxing
Unboxing
None
View all questions...
LINQ to SQL Best Practice
In this article we will see what all can be done to get maximum out of LINQ to SQL.
1.
Always try to have only one call to
SubmitChanges
. This will not only ensure that all the database operation are performed in one go, but will also maintain the Transaction of the all the operation
s
performed.
2.
While retrieving data from the database make sure to explicitly mention the column names that you want to retrieve instead of selecting all the data. This will reduce the amount of data flow and increase the performance of your application.
If I want only
Name
and
City
from a table having say 10 column use
var
result =
from
t
in
db.Countries
select
new
{
Name = t.Name,
ID = t.CountryID
}
Instead of
var
result =
from
t
in
db.Countries
select
t;
3.
Make sure to set the
Delay Loaded
property for the column, which carry large amount of data, to
False
.
This will ensure that data is not loaded into the memory till required.
4.
If you are dealing with a very complicated query, it's always advisable to write store procedure for the same and call it using LINQ. Idea behind is, when we go on to write such a complicated query using LINQ, we often land up write query which has poor performance and involves multiple call to database.
5.
LINQ work in deferred way, meaning the connection to database will not be open till we start iterating through the result and will not close the connection till this iteration is complete.
Hence if you are iterating through the loop to get the result make sure you don’t perform other lengthy operation inside the loop.(As connection will remain open till the loop ends)
6.
If it is required to do some lengthy processing it always better to call .ToList() or .ToArray() method which query the data immediately and return the strong typed collection which can be further used.
7.
Do not dump all your database table and Store Procedure into single class. As often there are number of Read only tables, tables that maintain the log information and not used extensively. These tables will unnecessary consume space in the memory and increase the identity management cost.
8.
It's always preferred to create two data context class. One that will have all the ready only data and other to store all the transactional data. By doing so we can increase the performance.
For the data context that has ready only table we can turn off the property
ObjectTrackingEnabled.
This will ensure that unnecessary Identity management is avoided
.
DataClasses1DataContext
datacontext =
new
DataClasses1DataContext
();
datacontext.ObjectTrackingEnabled =
false
;
9.
Turn off the Optimisting Concurrency unless you really need it. If application is desinged in a way to make sure that always the last update wins, there is no gain in doing an extra level of check.
[
Column
(Storage=
"_Name"
, DbType=
"NVarChar(50) NOT NULL"
, CanBeNull=
false
,
UpdateCheck=
UpdateCheck
.Never
)]
public
string
Name
{
get
{
return
this
._Name;
}
set
{
if
((
this
._Name !=
value
))
{
this
.OnNameChanging(
value
);
this
.SendPropertyChanging();
this
._Name =
value
;
this
.SendPropertyChanged(
"Name"
);
this
.OnNameChanged();
}
}
}
With respect to point 8 one can always set the attribute
UpdateCheck= UpdateCheck.Never
for all the columns of Ready only table.
10.
It's always a good idea to constantly monitor the query generated from the LINQ query that we write. This not only help one understand the behavior of LINQ in a better way but also helps to optimize the query. Its more about a standard process that one needs to follow in the initial stage of learning. Afterward it becomes a habit and one starts writing more optimized query.
11.
Use
CompiledQuery.Compile
to create a compiled version of query if you know that the query is going to get executed more than once. I say this because when query is generated for the first time, it takes more time than time required to generated normal query. There is a separate sections that deals in detail about the
CompiledQuery
.
12.
Use DataLoadOption when you want to retrieve all the data associated with given table. i.e. If you have a table Student and its has a mapping with Subject table, it always good to use DataLoadOption to pre fetch all the data beforehand. This will avoid multiple calls to database.
Ex.
DataLoadOptions
options =
new
DataLoadOptions
();
options.LoadWith<
Student
>(s => s.
Subject
);
context.LoadOptions = options;
IEnumerable
<
Student
> customers = context.
Student
.ToList<
Student
>();
13.
Further if you are aware that you need only part of the related data use
DataLoadOption.AssociateWith
. using this generic method one can easily filter out and get the required data.
Ex.
DataLoadOptions
option =
new
DataLoadOptions
();
option.AssociateWith<
Student
>(s => s.Subject.Where<
Subject
>(sb => sb.Id = 3));
14.
As by now we already know that LINQ has some performance overhead. Keeping this is mind its always better to fetch only required amount of data. Real time scenario is, while implementing paging in
GridView
make sure to fetch data that is equal to page size. Take() and Skip() method comes very handy in achieving this.
Comments
Sumit
Posted on:
10/24/2011 10:45:14 AM
Perfect!
Thanks.
Add Comment
Comment
Name
(Required)
E-mail
(Privacy assured)
(Required)
Subscribe to this site by email
Poll of the Day
Q.
Best Smart Mobile Phone in market?
I-Phone
Samsung
Nokia
Others
Related Contents
Online Test Papers
ASP.NET
JavaScript
LINQ
SharePoint
Silverlight
SQL
Related Tutorials
HTML 5 Tutorial
SharePoint Best Practice
How to add ribbon button in SharePoint list and library
List Join operation in SharePoint 2007 / 2010
ASP.NET 4.0 Tutorials
Fun @ Work
Keep smiling always
Developer Vs Tester
There are solutions, even to the hardest problems
Corporate Cartoons
Golden words of steve jobs
Top Blogs
SharePoint 2010 Modal Dialog
How to call webservice using Ajax or JavaScript
Microsoft OLE DB Provider for ODBC Drivers error 80004005
Using SQL SWITCH CASE Statement
Validation of viewstate MAC failed. If this application is hosted...
Creating a Windows Service in C#
Using InstallUtil to install/uninstall service
Each GROUP BY expression must contain at least one column that is not an outer reference
How to add ribbon button in SharePoint list and library
Client side onselectedindexchanged or onchange event in RadioButtonList
Arithmetic overflow error
Pass Data from Parent window to ChildWindow
Silverlight: ListBox with CheckBox
Tablix headers not repeating in SSRS 2008
LINQ to SQL Best Practice
Calling JavaScript function from C#
The contract name could not be found in the list of contracts implemented by the service
Like To Connect With US
x