Note that there are some explanatory texts on larger screens.

plurals
  1. POModify linq query at runtime
    primarykey
    data
    text
    <p><strong>Problem statement</strong></p> <p>Say I have a query which searches the names of people:</p> <pre><code>var result = (from person in container.people select person) .Where(p =&gt; p.Name.Contains(some_criterion) </code></pre> <p>This will be translated to a SQL query containing the following like clause:</p> <pre><code>WHERE NAME LIKE '%some_criterion%' </code></pre> <p>This has some performance implications, as the database is unable to effectively use the index on the name column (index scan v.s. index seek if I'm not mistaken).</p> <p>To remedy this, I can decide to just StartsWith() instead, generating a query using a like clause like:</p> <pre><code>WHERE NAME LIKE 'some_criterion%' </code></pre> <p>Which enables SQL server to use the index seek and delivering performance at the cost of some functionality.</p> <p>I'd like to be able to provide the user with a choice: defaulting the behavior to use StartsWith, but if the user want the 'added flexibility' of searching using Contains(), than that should used.</p> <p><strong>What have I tried</strong></p> <p>I thought this to be trivial and went on and implemented an extension method on string. But of course, LINQ does not accept this and an exception is thrown.</p> <p>Now, of course I can go about and use an if or switch statement and create a query for each of the cases, but I'd much rather solve this 'on a higher level' or more generically. In short: using an if statement to differentiate between use cases isn't feasible due to the complexity of the real-life application. This would lead to alot of repetition and clutter. I'd really like to be able to encapsulate the varying behavior (Contains, StartsWith, EndsWith) somehow.</p> <p><strong>Question</strong></p> <p>Where should I look or what should I look for? Is this a case for composability with IQueryables? I'm quite puzzled!</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.
 

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