Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a LINQ Expression where parameter equals object
    primarykey
    data
    text
    <p>Given a primitive value <code>age</code> I know how to create an expression like this:</p> <pre><code>//assuming: age is an int or some other primitive type employee =&gt; employee.Age == age </code></pre> <p>By doing this:</p> <pre><code>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); </code></pre> <p>That works fine except in scenarios where the property and constant in question are not primitive types.</p> <p>How would I construct a similar expression if the comparison is between objects?</p> <p>With EF I can just write:</p> <pre><code>Location location = GetCurrentLocation(); employees = DataContext.Employees.Where(e =&gt; e.Location == location); </code></pre> <p><strong>That also works</strong>, but if I try to create the same expression:</p> <pre><code>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); </code></pre> <p>I get an error that says:</p> <p><code>Unable to create a constant value of type 'Location'. Only primitive types or enumeration types are supported in this context.</code></p> <p>My suspicion is that <code>Expression.Constant()</code> only expects primitive types, so I need to use a different expression factory method. (maype <code>Expression.Object</code>? - I know that doesn't exist)</p> <p>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 statement, but not when it is an expression?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload