Linq to Sql - 如果where子句中的'contains'值为null,则返回所有数据

时间:2016-02-05 11:12:22

标签: c# asp.net contains

如果value(data.vendorname)为null,我需要获取所有vendorname,它给出一个错误异常:“Value不能为null。”

public HttpResponseMessage PostFilter([FromBody] dynamic data)
{
    string[] vendorname = data.vendorname != null
                          ? data.vendorname.ToObject<string[]>()
                          : null;

    var items = (from s in context.AllInventories
                 where
                    (vendorname!=null
                     ? vendorname.Contains(s.VENDORNAME)
                     :1==1)
                 select s)
                 .Take(500)
                 .ToList();
}

2 个答案:

答案 0 :(得分:2)

为什么不简化这一点,如果where为空,则根本不应用任何vendorname

public HttpResponseMessage PostFilter([FromBody] dynamic data)
{
    string[] vendorname = data.vendorname != null
                          ? data.vendorname.ToObject<string[]>()
                          : null;

    var query = context.AllInventories.AsQueryable();
    if (vendorname != null)
    {
        query = query.Where(s => vendorname.Contains(s.VENDORNAME));
    }

    var items = query.Take(500).ToList();
}

答案 1 :(得分:0)

为什么不使用简单的if语句?

IEnumerable<Inventory> inventories = context.AllInventories;
if(vendorname != null)
    inventories = inventories.Where(i => vendorname.Contains(i.VENDORNAME));             
inventories = inventories.Take(500).ToList(); 

这比希望你的sql技巧有效并且优化器足够聪明以忽略你的伪条件要好得多。调试也更好。