I play with expression trees and try to better understand how they work. I wrote an example of the code I'm working with, and hopefully someone can help me.
So, I have this somewhat dirty query:
public int GetMessageCountBy_Username(string username, bool sent)
{
var query = _dataContext.Messages
.Where(x => (sent ? x.Sender.ToLower() : x.Recipient.ToLower()) == username.ToLower())
.Count();
return query;
}
_dataContextis the context of the entity structure data. This query works beautifully, but is not easy to read. I decided to include the inline IF expression in the Funcfollowing way:
public int GetMessageCountBy_Username(string username, bool sent)
{
Func<Message, string> userSelector = x => sent ? x.Sender : x.Recipient;
var query = _dataContext.Messages
.Where(x => userSelector(x).ToLower() == username.ToLower())
.Count();
return query;
}
This seems to work fine, but there is a problem. Since the query is against IQueryable<T>, this LINQ expression is translated into SQL for execution in the data source. This is great, but because of this, he does not know what to do with the call userSelector(x)and throws an exception. He cannot translate this delegate into expression.
, , , , . , , . Func , SQL?
:
Expression<Func<Message, string>> userSelectorExpression = x => sent ? x.Sender : x.Recipient;
Func<Message, string> userSelector = userSelectorExpression.Compile();
, , . , . , , , , , . , userSelectorExpression LINQ, .
. . !
, , :
LINQ to Entities LINQ node type 'Invoke' .
, "" userSelector. , , .
:
LINQ to Entities 'System.String userSelector (Message, Boolean)', .