Wednesday, November 4, 2009

Dynamic LINQ

Guess whose back? ...
Alright, I shall stop before I get sued for copyright infringements

I was at work today and the boss decided to throw me a challenge. Basically, he wanted to custom-build a SQL query but instead of hitting the database, obtain the data from cache.

I suggested LINQ but as soon as I said that, I had to swallow my words as to my knowledge, LINQ allow filtering but not dynamically.

I trolled the web and discovered that Scott, did blog about this 2 years back. Yes, I know I am 2 years late but better than never, right?

You can find it @ Dynamic LINQ - Part 1

I did a basic LINQ query and use the Where method extension but still to no avail but after some more poking around the web, a break through!

This is how you do it.

1. Download the samples from the Dynamic LINQ url (see above).
2. Extract the Dynamic.cs file from the DynamicLinq directory and include that into your project.
3. In the work-space that you would like to use this powerful class, simply declare the following

IQueryable linqVar = from someLinqVar in YourObjectList.AsQueryable()
               select someLinqVar;
var otherLinqVar = linqVar.Where("whr clause with @val", param object[] paramValsArrayObj);

Note: the "val" in @val is of integer type that ties into the object array, paramValsArrayObj.

An example LINQ-WHERE clause will be as follows :-
"Value = @0 && Text = @1"

4. You will also have to include the System.Linq.Dynamic library in the Using clause at the very top of the intended work-space.

No comments:

Post a Comment