I have a method that takes Expression type parameter, in my method i want to get values of this expression but cant find out hot to do that.
private User GetUser(Expression<Func<User, bool>> query)
{
User user = Context.User.Where(query).FirstOrDefault();
return user;
}
I am calling this method with different parameters like
GetUser(u => u.Username == username);
GetUser(u=> u.Email == email);
I want to change GetUser method to work with stored procedures but i need to find what is inside query parameter
I want to check if query is u.Username == username I will call GetUserByUsername SP if query is u.Email == email I will call GetuserByEmail SP
The expression can be reduced to several expressions.
var body = query.Body as BinaryExpression;
if (body != null)
{
var left = body.Left as MemberExpression;
if (left != null)
{
Console.WriteLine(left.Member.Name);
// You can get "Username" or "Email" here
}
}
By the way I think you are in a wrong direction. Think about this situation: Some other developer see your GetUser
method, using it in this way:
var result = GetUser(u => u.Email.Equals("[email protected]")); //or
var another = GetUser(u => u.Username.Contains("bar"));
He would think he is correct, but in fact your method won't give his ideal result! Well you can say "never mind, I will inform them this change", but what about the days after you quitted this team/company? It's a nightmare if a method doesn't behave like its declaration.
Maybe you should use LINQ for SQL. It does exactly what you want: tear apart the expression and see what fields and comparisons you need. I don't suggest doing this manually, but if you want to, then look into the members of an Expression class, it's an expression tree and will have nodes like property access and comparison.
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