Tuesday, December 27, 2011

Using LINQ To SQL CompiledQuery

CompliedQuery increase performance by compiling the query one time and executing it several times with different parameters.

With CompliedQuery , you compile your query once and store it somewhere for later usage. This is achieved by static CompliedQuery.Compile method.

It provides for compilation and caching of queries for reuse.
To compile the query, we have to use the CompiledQuery.Compile method. This method takes an argument list as input and a result type.

Below is simple Example.

The following example compiles and then invokes a query that  returns a List of employees where employeeid=1.

public static Func<TestDataContext, IEnumerable<Employee>> GetEmployeeList
                return CompiledQuery.Compile<TestDataContext, IEnumerable<Employee>>
                    ((TestDataContext context) => context.Employees.Where<Employee>(x => x.EmployeeID== 1));

In above code, i created DBML DataContext named TestDataContext that contains all tables.

I have created class named Employee to use in result set.

No comments:

Post a Comment