I'm trying to mimic the LINQ Where extension method for my ADO.NET DAL methods.
Bascially, my aim is to have a single method that I can call. Such as:
Product p = Dal.GetProduct(x => x.ProductId == 32);
Product p2 = Dal.GetProduct(x => x.ProductName.Contains("Soap"));
I then want to dissect those Predicates and send the filter options to parameters in an ADO.NET Stored Procedure call.
Any comments greatly appreciated.
As @Daniel points out, this is far from simple. The solution outline is to let GetProduct
take an argument of type Expression<Func<Product, bool>>
. You then have to traverse the parse-tree of this expression, generating the correct SQL for functions known and also decide how to handle unknown functions. There are basically two options for that:
It would be a fun exercise to do it - but I can hardly see a way to justify it in the real world, when there are already linq2sql, linq2entities and linq2NHibernate that does the job.
In addition to Anders's answer, I just want to mention that you can analyze the expression tree by using an expression visitor. To do that, you can inherit the ExpressionVisitor
class (it's new in .NET 4, but you can find a 3.5 implementation in LinqKit) and override the methods you want to analyze each node.
You might also be interested in those links :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With