首先要做的是进行日志记录,以查看生成了什么TSQL。例如:
ctx.Log = Console.Out;
LINQ-to-SQL似乎对null的处理有些不一致(取决于文字与值):
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 => x.ReportsTo == (int?)null).ToList(); // 0 rows: var bosses2 = ctx.Employees.Where(x => x.ReportsTo == mgr).ToList();}
因此,我只能建议使用带空值的顶级表格!
即
expression<Func<Category,bool>> predicate;if(categoryId == null) { predicate = c=>c.ParentId == null;} else { predicate = c=>c.ParentId == categoryId;}var subCategories = this.Repository.Categories.Where(predicate).ToList().Cast<ICategory>();
更新-我使用自定义功能使其“正常”工作
expression:
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 => x.ReportsTo, manager).ToList(); Console.WriteLine(emps.Count); } } static IQueryable<T> Where<T, TValue>( this IQueryable<T> source, expression<Func<T, TValue?>> 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<Func<T,bool>>(body, param); return source.Where(lambda); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)