创建动态LINQ查询以满足不同条件

时间:2015-11-19 11:50:58

标签: c# winforms linq entity

我有一个LINQ查询来填充一个对象(这是一个网格的数据源),只有少量连接。

我希望查询是动态的,因此它会根据传递的参数检索行,但到目前为止,只要传入StatusID,它就无法工作 - 它会带回所有实例(就像一个cartesion产品是发生)

_viewfetch.POMastStatusID将为-1或值为1或更高。

QUERY:

var queryforobject = from p in db.POMasts.AsNoTracking()
                     join pr in db.Profiles.AsNoTracking() on p.ProfileID equals pr.ID
                     join c in db.CurrencyTypes.AsNoTracking() on p.CurrencyTypeID equals c.ID
                     join w in db.WHMasts.AsNoTracking() on p.WarehouseID equals w.ID
                     join t in db.TermCodeTypes.AsNoTracking() on p.TermCodeTypeID equals t.ID
                     join s in db.POMastStatusTypes.AsNoTracking() on p.StatusID equals s.ID

                     //Ensure that these are dynamic
                     where _viewfetch.VendMastID == -1 || p.VendorID == _viewfetch.VendMastID && 
                     _viewfetch.POMastStatusID == -1 || p.StatusID == _viewfetch.POMastStatusID

                     orderby p.ID

                     //Put the query results into the bespoke object
                     select new POMastObject { ID = p.ID, 
                                               OrderNo = p.OrderNo, 
                                               RaisedDate = p.RaisedDate, 
                                               RaisedBy = pr.Name, 
                                               Currency = c.Description, 
                                               Warehouse = w.Description, 
                                               Terms = t.Description, 
                                               LastEditedBy = p.LastEditedBy, 
                                               LastEditedDate = p.LastEditedDate, 
                                               Status = s.Name };
if (queryforobject.Count() > 0)
    _dataobject = queryforobject.ToList();

有人有任何建议吗?

1 个答案:

答案 0 :(得分:1)

您的查询很好,它只是在&&运算符的两个部分周围缺少括号:

 where (_viewfetch.VendMastID == -1 || p.VendorID == _viewfetch.VendMastID) && 
       (_viewfetch.POMastStatusID == -1 || p.StatusID == _viewfetch.POMastStatusID)

由于&&的优先级高于||,因此您的查询会有效地评估中间AND-ed中的两个条件,如下所示:

_viewfetch.VendMastID == -1 || (p.VendorID == _viewfetch.VendMastID && _viewfetch.POMastStatusID == -1) || p.StatusID == _viewfetch.POMastStatusID

这不是您正在寻找的逻辑,因为当VendMastID-1时,您将获得所有行。