Reputation: 465
I try to creat an expression for Linq query dynamically but it gives just this message back:
{Method = Internal Error evaluating expression} I use Vs 2019 and .NET Core 3.1. class Client { public string Name { get; set; } ... }
var parameter = Expression.Parameter(typeof(Client), "x");
var member = Expression.Property(parameter, "Name");
var constant = Expression.Constant("X Y");
var exp = Expression.Equal(member, constant);
var func = Expression.Lambda(exp, parameter).Compile();
Where do I make a mistake, please?
UPDATE
namespace Domain
{
public class Client
{
public string Name { get; set; }
public string UserName { get; set; }
public string Department { get; set; }
public string CompanyPhoneNumber { get; set; }
public string PrivateMobileNumber { get; set; }
public string ComputerName { get; set; }
public Guid InternetProviderId { get; set; }
public virtual InternetProvider InternetProvider { get; set; }
public string OtherInternetProvider { get; set; }
}
}
Upvotes: 0
Views: 408
Reputation: 9490
Expression.Lambda
method has a generic version that allows to specify the delegate type, the last line can be modified to:
var func = Expression.Lambda<Func<Client, bool>>(exp, parameter).Compile();
Example of use:
var list = new List<Client>
{
new Client() { Name = "X Y"}
};
var l2 = list.Where(func).ToList();
Working example: here.
Upvotes: 1