Reputation: 1575
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.
Upvotes: 2
Views: 1397
Reputation: 564433
You should use an expression directly:
public bool Update<T>(T obj, Expression<Func<T, bool>> predicate)
You would call this the same way:
Update(obj, o => o.Id = 1);
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 = 1
result.
Upvotes: 6
Reputation: 887469
It is completely impossible to create an expression tree from a delegate.
Instead, you need to change your method to take an expression tree.
The compiler will allow callers to pass a lambda expression as the parameter, which will compile to an expression tree.
Upvotes: 1