.NET (296) administrative (41) Ajax (42) AngularJS (2) ASP.NET (144) bicycle (2) books (180) browser (8) C# (134) cars (1) chess (28) CodePlex (10) Coma (8) database (47) deployment (3) Entity Framework (2) essay (112) flash/shockwave (2) flex (1) food (3) friend (2) game (20) idea (5) IIS (8) javascript (82) LInQ (2) Linux (6) management (4) manga (42) misc (672) mobile (1) movies (91) MsAccess (1) murder (2) music (64) mysql (1) news (100) permanent (1) personal (68) PHP (1) physics (2) picture (307) places (12) politics (13) programming (504) rant (120) religion (3) science (43) Sharepoint (3) software (58) space (1) T4 (2) technology (11) Test Driven Development (4) translation (2) VB (2) video (97) Visual Studio (44) web design (46) Windows API (8) Windows Forms (3) Windows Server (5) WPF/Silverlight (63) XML (11)

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.

No comments: