Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5950749
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T17:26:16+00:00 2026-05-22T17:26:16+00:00

I am playing around with expression trees and trying to better understand how they

  • 0

I am playing around with expression trees and trying to better understand how they work. I wrote some sample code that I’m working with and hopefully someone can help me out.

So I have this somewhat messy query:

/// <summary>
/// Retrieves the total number of messages for the user.
/// </summary>
/// <param name="username">The name of the user.</param>
/// <param name="sent">True if retrieving the number of messages sent.</param>
/// <returns>The total number of messages.</returns>
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;
}

_dataContext is the entity framework data context. This query works beautifully, but it’s not easy to read. I decided to factor the inline IF statement out into a Func like this:

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 like it would work great, but there is a problem. Because the query is against IQueryable<T> this LINQ expression is being translated into SQL to be executed at the data source. That’s great, but because of this it does not know what to do with the call to userSelector(x) and throws an exception. It cannot translate this delegate into an expression.

So now that I understand why it’s failing I would like to try and make it work. It’s far more work for what I need, but I’m doing it just out of pure interest. How might I turn this Func into an expression that can be translated into SQL?

I tried to do this:

Expression<Func<Message, string>> userSelectorExpression = x => sent ? x.Sender : x.Recipient;
Func<Message, string> userSelector = userSelectorExpression.Compile();

With this however, I get the same error. I think I’m failing to understand expressions. I think all I’m doing with the above code is writing an expression but then turning it into executable code again and then getting the same error. However, if I try to use userSelectorExpression within the LINQ query it can’t be called like a method.

Edit

For those interested in the exception, here it is:

The LINQ expression node type ‘Invoke’ is not supported in LINQ to Entities.

I took this to mean that it could not "invoke" the userSelector delegate. Because, as stated above, it needs to translate it into an expression tree.

When using a real method, you get a slightly more verbose error message:

LINQ to Entities does not recognize the method ‘System.String userSelector(Message, Boolean)’ method, and this method cannot be translated into a store expression.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T17:26:17+00:00Added an answer on May 22, 2026 at 5:26 pm

    Well after playing around a bit, I got what I wanted.

    This didn’t save me tons of code in this case, but it does make the base query much easier to look at. For more complicated queries in the future this will be awesome! This query logic never gets repeated, but still gets re-used as many times as I need to.

    First I have two methods in my repository. One counts the total number of messages (the one I used as the example in my question) and one that actually gets a collection of messages by page number. Here is how they are structured:

    The one that gets a total count of messages:

        /// <summary>
        /// Retrieves the total number of messages for the user.
        /// </summary>
        /// <param name="username">The name of the user.</param>
        /// <param name="sent">True if retrieving the number of messages sent.</param>
        /// <returns>The total number of messages.</returns>
        public int GetMessageCountBy_Username(string username, bool sent)
        {
            var query = _dataContext.Messages
                .Count(UserSelector(username, sent));
            return query;
        }
    

    The one that gets messages and pages them:

        /// <summary>
        /// Retrieves a list of messages from the data context for a user.
        /// </summary>
        /// <param name="username">The name of the user.</param>
        /// <param name="page">The page number.</param>
        /// <param name="itemsPerPage">The number of items to display per page.</param>
        /// <returns>An enumerable list of messages.</returns>
        public IEnumerable<Message> GetMessagesBy_Username(string username, int page, int itemsPerPage, bool sent)
        {
            var query = _dataContext.Messages
                .Where(UserSelector(username, sent))
                .OrderByDescending(x => x.SentDate)
                .Skip(itemsPerPage * (page - 1))
                .Take(itemsPerPage);
            return query;
        }
    

    Obviously it is the call to UserSelector(string, bool) that is the big deal here. Here is what that method looks like:

        /// <summary>
        /// Builds an expression to be reused in a LINQ query.
        /// </summary>
        /// <param name="username">The name of the user.</param>
        /// <param name="sent">True if retrieving sent messages.</param>
        /// <returns>An expression to be used in a LINQ query.</returns>
        private Expression<Func<Message, bool>> UserSelector(string username, bool sent)
        {
            return x => ((sent ? x.FromUser : x.ToUser).Username.ToLower() == username.ToLower()) && (sent ? !x.SenderDeleted : !x.RecipientDeleted);
        }
    

    So this method builds an expression to be evaluated and properly gets translated into it’s SQL equivalent. The function in the expression evaluates to true if the username matches the username of either the sender or the recipient and deleted is false for either sender or recipient, based on the supplied boolean sent that gets serialized into the expression.

    Here is a version of the above, that is closer to the example in my question. It’s not as readable since my expression is grotesque but at lease I understand how it’s working now:

        public int GetMessageCountBy_Username(string username, bool sent)
        {
            Expression<Func<Message, bool>> userSelector = x => ((sent ? x.FromUser : x.ToUser).Username.ToLower() == username.ToLower()) && (sent ? !x.SenderDeleted : !x.RecipientDeleted);
    
            var query = _dataContext.Messages
                .Count(userSelector);
            return query;
        }
    

    This is actually pretty cool stuff. Took a lot of time to figure out but this seems really powerful. I now have a new understanding of how LINQ, lambdas, and expressions work 🙂

    Thanks to everyone who contributed to this question! (including you artplastika, I still love you even if I don’t love your answer)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've been playing around with Expression Trees. I have the following simple method that
I was playing around with expression trees and various Linq syntax. I wrote the
I was playing around with .Net reflector today and realized that Miicrosoft's entire Expression
Just playing around with java trying to learn it etc. Here is my code
When playing around with Pointfree I was presented with a piece of code that
I was playing around with DynamicMethod and Expression Trees ' Compilation (which uses DynamicMethod
Playing around with MongoDB and NoRM in .NET. Thing that confused me - there
Just playing around with the now released Silverlight 2.0. I'm trying to put a
While playing around with regexps in Scala I wrote something like this: scala> val
I'm playing around with the <canvas> element, drawing lines and such. I've noticed that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.