6

How can I get values ​​from Linq Expression?

 2 years ago
source link: https://www.codesd.com/item/how-can-i-get-values-from-linq-expression.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How can I get values ​​from Linq Expression?

advertisements

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK