Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a custom LINQ-to-X provider

Tags:

.net

linq

I've got a search tool which takes a complex search string (actually, an n-level object graph in JSON) and returns some results. I want to expose the functionality to other (internal) developers through a LINQ-like mechanism.

Assuming each result is defined by a class Result

I can create methods look something like:

Function Search(Expression As Linq.Expression(Of System.Func(Of Result, Boolean))) As IEnumerable(Of Result)

What I'm unclear of is how I can walk that Expression parameter and extract the actual criteria which I can then form into the object graph for running my query.

Can someone point me at a tutorial/example of how this can be achieved?

For a little background, I've managed to dig into the expression far enough to get the recursive structure and am able to examine the .Body of lambda expressions but when I get as far as wanting to handle the Left and Right properties of a Node with eg type ExpressionType.Or, I'm having issues. The debugger is using a Friend-scoped class (BinaryExpressionProxy) to examine the expression which isn't available to me so I'm clearly heading down the wrong route.

like image 815
Basic Avatar asked Aug 29 '12 15:08

Basic


2 Answers

You may want to look at subclassing the ExpressionVisitor class. This provides the mechanism to walk the expression tree, all you have override the methods to process each type of node.

Here are some other links you may find helpful:

  • Expression Tree Docs:

    • VB
    • C#
  • Expression Tree Basics (blog post)

like image 176
luksan Avatar answered Oct 20 '22 01:10

luksan


You can try using a project I wrote called LinqToAnything which you can use to wrap datasources to expose an IQueryable, depending on your needs.

like image 31
mcintyre321 Avatar answered Oct 19 '22 23:10

mcintyre321