本文介绍了Linq to Sql在Where子句中为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果Sessions.Current.AdminProductId为null,是否可以忽略Where子句?我想将下面的代码优化为一行代码.

Is it possible to ignore Where clause if Sessions.Current.AdminProductId is null? I would like to optimize code below into one line of code.

if (Sessions.Current.AdminProductId == null)
  gvUsers.DataSource = DataAccess.Instance.Users;
else
  gvUsers.DataSource = DataAccess.Instance.Users.Where(p => p.Orders.Any(o => o.ProductId == Sessions.Current.AdminProductId));

推荐答案

您只需要在where子句中添加null检查,就像这样:

You just need to add the null check in the where clause like this:

 gvUsers.DataSource = DataAccess.Instance.Users.Where(p => (Sessions.Current.AdminProductId == null) || (Sessions.Current.AdminProductId != null && p.Orders.Any(o => o.ProductId == Sessions.Current.AdminProductId)));

这篇关于Linq to Sql在Where子句中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:22