Linq to Sql在Where子句中为null

时间:2012-01-09 08:36:07

标签: linq-to-sql

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

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));

1 个答案:

答案 0 :(得分:2)

您只需要在where子句中添加null检查,如下所示:

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