Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The first thing to do is to put on logging, to see what TSQL was generated; for example:</p> <pre><code>ctx.Log = Console.Out; </code></pre> <p>LINQ-to-SQL seems to treat nulls a little inconsistently (depending on literal vs value):</p> <pre><code>using(var ctx = new DataClasses2DataContext()) { ctx.Log = Console.Out; int? mgr = (int?)null; // redundant int? for comparison... // 23 rows: var bosses1 = ctx.Employees.Where(x =&gt; x.ReportsTo == (int?)null).ToList(); // 0 rows: var bosses2 = ctx.Employees.Where(x =&gt; x.ReportsTo == mgr).ToList(); } </code></pre> <p>So all I can suggest is use the top form with nulls!</p> <p>i.e.</p> <pre><code>Expression&lt;Func&lt;Category,bool&gt;&gt; predicate; if(categoryId == null) { predicate = c=&gt;c.ParentId == null; } else { predicate = c=&gt;c.ParentId == categoryId; } var subCategories = this.Repository.Categories .Where(predicate).ToList().Cast&lt;ICategory&gt;(); </code></pre> <hr> <p>Update - I got it working "properly" using a custom <code>Expression</code>:</p> <pre><code> static void Main() { ShowEmps(29); // 4 rows ShowEmps(null); // 23 rows } static void ShowEmps(int? manager) { using (var ctx = new DataClasses2DataContext()) { ctx.Log = Console.Out; var emps = ctx.Employees.Where(x =&gt; x.ReportsTo, manager).ToList(); Console.WriteLine(emps.Count); } } static IQueryable&lt;T&gt; Where&lt;T, TValue&gt;( this IQueryable&lt;T&gt; source, Expression&lt;Func&lt;T, TValue?&gt;&gt; selector, TValue? value) where TValue : struct { var param = Expression.Parameter(typeof (T), "x"); var member = Expression.Invoke(selector, param); var body = Expression.Equal( member, Expression.Constant(value, typeof (TValue?))); var lambda = Expression.Lambda&lt;Func&lt;T,bool&gt;&gt;(body, param); return source.Where(lambda); } </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.
    3. 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