Given a primitive value age I know how to create an expression like this:

//assuming: age is an int or some other primitive type
employee => employee.Age == age

By doing this:

var entityType = typeof(Employee);
var propertyName = "Age";
int age = 30;
var parameter = Expression.Parameter(entityType, "entity");

var lambda = Expression.Lambda(
        Expression.Equal(
            Expression.Property(parameter, propertyName),
            Expression.Constant(age)
        )                    
    , parameter);

That works fine except in scenarios where the property and constant in question are not primitive types.

How would I construct a similar expression if the comparison is between objects?

With EF I can just write:

Location location = GetCurrentLocation();
employees = DataContext.Employees.Where(e => e.Location == location);

That also works, but if I try to create the same expression:

var entityType = typeof(Employee);
var propertyName = "Location";
var location = GetCurrentLocation();
var parameter = Expression.Parameter(entityType, "entity");

var lambda = Expression.Lambda(
        Expression.Equal(
            Expression.Property(parameter, propertyName),
            Expression.Constant(location)
        )                    
    , parameter);

I get an error that says:

Unable to create a constant value of type 'Location'. Only primitive types or enumeration types are supported in this context.

My suspicion is that Expression.Constant() only expects primitive types, so I need to use a different expression factory method. (maype Expression.Object? - I know that doesn't exist)

Is there a way to create an expression that compares objects? Why is that EF is able to interpret it correctly if its a compiled LINQ stateme

Edit
Report