Note that there are some explanatory texts on larger screens.

plurals
  1. POIQueryable extension method for linq2entities
    text
    copied!<p>I am trying to implement an extension method that will work with linq2entities. I had initially assumed that if my extension method took and returned an IQueryable, and as long as my expression only made use of supported methods, then it would work fine. I was having alot of trouble, so as a last resort I copied an existing .NET extension method that I knew to work(FirstOrDefault) and simply renamed it. It would seem like it would evaluate the "cannot be translated into a store expression" validation based on the expression returned from the method, not the name of the method itself.</p> <pre><code>var prs = db.People.Where(p =&gt; p.PersonKey == 15).Select(p =&gt; new { id = p.PersonKey, name1 = p.PersonHistories.AsQueryable().AsOf().Name } ).ToList(); </code></pre> <p>My extension method, which is just a copy of FirstOrDefault that I renamed:</p> <pre><code>public static TSource AsOf&lt;TSource&gt;(this IQueryable&lt;TSource&gt; source) { return source.Provider.Execute&lt;TSource&gt;(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(new Type[] { typeof(TSource) }), new Expression[] { source.Expression })); } </code></pre> <p>Error:</p> <pre><code>LINQ to Entities does not recognize the method 'Models.PersonHistory AsOf[PersonHistory](System.Linq.IQueryable`1[Models.PersonHistory])' method, and this method cannot be translated into a store expression. </code></pre> <p>How do I implement an IQueryable extension method that is supported in Linq2Entities?</p> <p>What I really want AsOf(source, DateTime asOf) to do is soemthing like <code>source.FirstOrDefault&lt;IHistory&gt;(s =&gt; s.EndDate &gt; asOf &amp;&amp; asOf &gt;= s.StartDate )</code>, but I'm not sure how to accomplish this so that it is supported by linq2entities.</p> <p><strong>LINQKIT:</strong> This is what I've come up with using linqkit and I'm hoping somehow I can factor this into something more reusable:</p> <pre><code>Expression&lt;Func&lt;PersonHistory, bool&gt;&gt; IsCurrent = (p) =&gt; p.Ends &gt; DateTime.Now &amp;&amp; p.Starts &lt;= DateTime.Now; var query = db.PersonHistories.Where(IsCurrent); </code></pre> <ol> <li>Have a more globally declared expression, instead of a local variable.</li> <li>Add a DateTime asOf parameter, instead of having .Now hard coded.</li> <li>And if possible, adapt it into an extension method(this sort of is the same as #1, just that an extension method is ideal.</li> </ol>
 

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