Note that there are some explanatory texts on larger screens.

plurals
  1. POOptions for code sharing in Linq2SQL expressions
    text
    copied!<p>I have a pair of Linq to SQL queries which contain the same complex Where clause, specifically:</p> <pre><code>where ((range.MinimumFrequency &lt;= minFreq &amp;&amp; minFreq &lt;= range.MaximumFrequency) || (range.MinimumFrequency &lt;= maxFreq &amp;&amp; maxFreq &lt;= range.MaximumFrequency) || (range.MinimumFrequency &lt;= minFreq &amp;&amp; maxFreq &lt;= range.MaximumFrequency) || (range.MinimumFrequency &gt;= minFreq &amp;&amp; maxFreq &gt;= range.MaximumFrequency)) </code></pre> <p>And rather than copy and paste this chunk of code all over the place, I wanted to refactor it out into something else that can be shared. I know I can't do this with a normal method as it cannot be translated into SQL, but I also can't get the </p> <blockquote> <p>Expression &lt; Func&lt;...>></p> </blockquote> <p>things <a href="http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/ce3e3721-ded0-4dc6-a40a-ddeb981c2ebe/" rel="nofollow noreferrer">described here</a> to work either.</p> <p>If I simplify the where clause for the purpose of my sanity here, I want to turn</p> <pre><code>where (range.MinumumFrequency &lt; minFreq) </code></pre> <p>into an expression, so I tried:</p> <pre><code>public static Expression&lt;Func&lt;FreqRange, bool&gt;&gt; Overlaps(decimal minMHz, decimal maxMHz) { return (range =&gt; range.MinimumFrequency &lt;= minMHz); } </code></pre> <p>This appears to compile, but I can't seem to get the where statement to work, I have tried the following:</p> <pre><code>where FreqRange.Overlaps(minMHz, maxMHz) </code></pre> <p>but this gives me a compile time error:</p> <blockquote> <p>Cannot implicitly convert type 'System.Linq.Expressions.Expression>' to 'bool'</p> </blockquote> <p>Any ideas? Also, assuming we get this working, can I simply extend the lambda expression in the Expression &lt; Func &lt;>> to include the other conditions?</p>
 

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