Monday, May 25, 2009

LinqKit - a Linq library for power users

I was trying to do something that is usually a drag: create a query with variable parameters. Something like Google search, where each query has a number of words and you want to search for each of them. How can one do this with Linq? More than that, Linq to Entities, which is pretty much making my life hell nowadays.

The idea would be to start with a IQueryable object and keep adding queries to it. This isn't so bad when you want to do an AND operation between your individual query strings.
var dc=new MyEntities();
var content=dc.Content;
foreach (var filter in filters) content=content.Where(c=>c.Text.Contains(s));

But what if you want to do an OR operation? Then you would want to be able to add stuff to the lambda inside a singe Where method. I won't get into the details, rather give you a link. I am not an expert on this myself, so it would be pointless. The more important thing is that you can do this a lot easier by using a library called LinqKit, which adds some very useful extension methods for Linq, enabling you to dynamically create queries, lambdas, etc.

There are other 'lighter' versions of this method on the Internet, unfortunately most of them are usable only with Linq to SQL, not the Entity Framework. For example I've read an interesting blog entry about this, tried the code, and got an ugly error: "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities". LinqKit also did this in its earlier versions, but the Albahari brothers fixed it. So, as far as I can see, I recommend this library for real life linq composition.