值不能为null,paramName:LINQ中的值

时间:2017-12-19 19:45:55

标签: c# asp.net-mvc linq

我的linq where子句有问题。代码:

public IEnumerable<SearchResult> Search(int? orderId, string customer, string car, int? type, int? status, string sortBy = null)
    {

        var records = Orders.Where(x => (x.Id == orderId || orderId == null) &&
                                        (string.Format("{0} {1}", x.Customer.Name, x.Customer.Surname).Contains(customer) || string.IsNullOrEmpty(customer)) &&
                                        (string.Format("{0} {1}", x.Car.Mark, x.Car.Model).Contains(car) || string.IsNullOrEmpty(car)) &&
                                        (x.OrderType.Id == type || type == null) &&
                                        (x.OrderStatus.Id == status || status == null));


    }

问题在于orderId,类型和状态。 VS像title中一样抛出异常:value不能为null,paramName:value。这很奇怪,因为当我开始搜索时,这些参数(orderId,type,status)在初始化时必须为null。

2 个答案:

答案 0 :(得分:1)

如果您将null传递给String.Contains方法,则会抛出&#34; Value cannot be null. ParamName: Value.&#34;例外。 话虽如此,我怀疑customercar参数为空。

答案 1 :(得分:1)

包含在字符串中使用时不喜欢NULL,并且假设所有参数都可以为空,您可以将查询分开,如下所示:

public IEnumerable<SearchResult> Search(int? orderId, string customer, string car, int? type, int? status, string sortBy = null)
{

  var records = Orders;

  if(orderId!=null)
  {
    records=records.Where(x=>x.Id == orderId);
  }

  if(!string.IsNullOrWhiteSpace(customer))
  {
     records=records.Where(string.Format("{0} {1}", x.Customer.Name, x.Customer.Surname).Contains(customer));
  }

.. and so on

}

我认为你可以获得性能,因为要求每个参数都会阻止迭代每个要求其值的项目