LINQ Select expression IEnumerable-Collection of common programming errors

Please have a look at Why would you use Expression rather than Func?.

The accepted answer describes that Func is a delegate to a method that returns a T. Expression however is actually a description of how that delegate can be evaluated. You can for example compile an expression into an actual delegate:

Expression expr = i => i < 5;
Func deleg = expr.Compile();
Console.WriteLine("deleg(4) = {0}", deleg(4));

You can even write:

Console.WriteLine("deleg(4) = {0}", expr.Compile()(4));

So if you really need an expression you need to compile it into the actual delegate otherwise use the delegate in the first place.

(BTW: Your code example won’t compile since there is no Select method for a List that takes an expression and also d => d.user.username is probably wrong. Since d is a user it should be d => d.username).

However linq to entities does not support delegate calls. Therefore you have to switch to linq to objects by adding AsEnumerable():

Expression expr = d => d.username;
Func func = expr.Compile();

var result = context.Message.AsEnumerable()
                            .Select(b => new { name = b.user.Select(func) });

Use linq to entities for accessing the data, simple ordering, filtering etc. This way it can optimize the queries for the database but then switch to linq to objects if you need more.

PS: The lambda d => d.username is compiled into a delegate. If you explicitly put it into the expression b.user.Select(u => u.username) it will work fine because now this also compiles into an expression that linq to entities can handle without calling a delegate.