Lambda Expressions and Stored Procedures

I am trying to imitate the LINQ Where extension method for my ADO.NET DAL methods.

Basically, my goal is to have a single method that I can name. For instance:

Product p = Dal.GetProduct(x => x.ProductId == 32); Product p2 = Dal.GetProduct(x => x.ProductName.Contains("Soap")); 

Then I want to analyze these predicates and send the filter parameters to the parameters in the ADO.NET stored procedure call.

Any comments are greatly appreciated.

+4
source share
2 answers

As Daniel notes, this is far from easy. The solution outline should allow GetProduct to take an argument of type Expression<Func<Product, bool>> . Then you need to parse this expression by creating the correct SQL for the known functions and also deciding how to handle the unknown functions. There are two options for this:

  • Throw an error (as linq-to-sql does).
  • Skip it in the translation, and then apply it to the returned result. The effective impact of this can, of course, be enormous if a lot of data is restored only for filtering.

It would be fun to do this exercise, but I can hardly justify it in the real world when there are already linq2sql, linq2entities and linq2NHibernate that do the job.

+9
source

In addition to Anders' answers, I just want to mention that you can parse an expression tree using an expression visitor. To do this, you can inherit the ExpressionVisitor class (it is new in .NET 4, but you can find the 3.5 implementation in LinqKit ) and override the methods that you want to analyze each node.

You may also be interested in these links:

+4
source

Source: https://habr.com/ru/post/1310147/


All Articles