Note that there are some explanatory texts on larger screens.

plurals
  1. POExpression tree and AND condition
    primarykey
    data
    text
    <p>i'm trying to build a filter expression to filter data from the database.</p> <p>I've wrote the following extension to build expression dynamically depending on the selected filter parameters:</p> <pre><code>public static Expression&lt;Func&lt;T, bool&gt;&gt; And&lt;T&gt;( this Expression&lt;Func&lt;T, bool&gt;&gt; leftExpression, Expression&lt;Func&lt;T, bool&gt;&gt; rightExpression) { var invocationExpression = Expression.Invoke(rightExpression, leftExpression.Parameters.Cast&lt;Expression&gt;()); var andExpression = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;( Expression.AndAlso(leftExpression.Body, invocationExpression), leftExpression.Parameters); return andExpression; } </code></pre> <p>I'm using it in such way:</p> <pre><code>Expression&lt;Func&lt;MyObject, bool&gt;&gt; expression = x =&gt; true; if(MyFilter.SomeParam) { expression = expression.And(x=&gt;x.MyProperty == MyFilter.SomeParam); } </code></pre> <p>It works great with NHibernate, but when i'm using this code with Entity Framework 5 it fails with the following exception message:</p> <blockquote> <p>The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.</p> </blockquote> <p>There is one workaround that fetches the whole collection from the database and then applies filter conditions through the <code>IEnumerable.Where(Func&lt;T1, T2&gt; filterClause)</code>, but it dont need all data just to get one record while <code>Expression&lt;Func&lt;T1, T2&gt;&gt;</code> expressions are translated directly into SQL statement.</p> <p>Is there any simple way to make this code work with Entity Framework?</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.
    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