Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've done something similiar to this in a project recently. What I ended up doing was implementing the repository pattern and created a method on the repository called "ApplyFilter" which looked something like:</p> <pre><code>void ApplyFilter(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate) { if(this.resultSet == null) { this.resultSet = this.context.Set&lt;TEntity&gt;().AsQueryable(); } this.resultSet = this.resultSet.Where(predicate); } </code></pre> <p>And had a property on my repository called "ResultSet" which just returned the IQueryable&lt;TEntity&gt; resultSet field and forced an enumeration of the results (triggering EF's database call). This way I could apply all the dynamically created expressions in a clean why before enumerating the results.</p> <p>The real difference between what my code does and what yours is doing is my code appends the boolean predicate to the final Expression tree where as you are trying to use yours within the final expression tree. My way basically creates/appends a WHERE clause to the SQL, yours tries to generate a SQL function call from the "DatesBetween" method.</p> <p>Here is something to try:</p> <pre><code> public static Expression&lt;Func&lt;TEntity, bool&gt;&gt; MakeDateRange&lt;TEntity&gt;(DateTime? dateFrom, DateTime? dateTo) { var et = typeof(TEntity); var param = Expression.Parameter(et, "a"); var prop = et.GetProperty("UpdatedDate"); Expression body = null, left = null, right = null; if (prop == null) { prop = et.GetProperty("CreatedDate"); if (prop == null) { prop = et.GetProperty("Date"); } } if (dateFrom.HasValue) { left = Expression.GreaterThanOrEqual(Expression.PropertyOrField(param, prop.Name), Expression.Constant(dateFrom.GetValueOrDefault())); } if (dateTo.HasValue) { right = Expression.LessThanOrEqual(Expression.PropertyOrField(param, prop.Name), Expression.Constant(dateTo.GetValueOrDefault())); } if (left != null &amp;&amp; right != null) { body = Expression.AndAlso(left, right); } else if (left != null) { body = left; } else { body = right; } return Expression.Lambda&lt;Func&lt;TEntity, bool&gt;&gt;(body, param); } </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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