I’m working on a little helper for adding, editing and removing objects from a database, the add method is working right now and given an object of type t, it checks the properties, the values, and generates a SQL Query to insert the data into a table (it assumes the table name is the type from the object, but can also be set manually)
What I want to do now is a method
public bool Update<T>(T obj, Func<T, bool> predicate)
So given an T obj, and a lambda function predicate, if predicate is
(o => o.Id = 1)
I want to generate
WHERE Id = 1
I’ve seen some similar questions, and I think expression trees might be a good starting point, but all I’ve seen is how to manually create an expression, not how to create an expression from a delegate.
Is there a way to generate that SQL from the delegate?
EDIT: I finally could do what I wanted, and I made a little post about that here.
You should use an expression directly:
You would call this the same way:
This will provide you the full expression tree, which you can then decipher and translate into your SQL. The compiler will build the expression tree from a lambda, just like it does with the
Func<T,bool>delegate.Once you have the expression tree, in your case, you should be able to create an ExpressionVisitor to parse the tree, and find all of the Where statements to convert to your
WHERE Id = 1result.