我正在寻找有关如何过滤以下LINQ查询的建议。 您可以看到涉及6个表,从中选择的表是b - 预订。 然后,根据传入的变量是否为null,我添加WHERE子句,但据我所知,如果我从b中选择,那么我只能将WHERE子句添加到b,所以如果我想添加WHERE到任何其他连接表如何在LINQ中执行此操作?
public List<DAL.Booking> GetBookingMain(string _booking, string _project, string _customer, string _location,
string _supplierSKU, string _eisSKU, string _assetREF)
{
List<DAL.Booking> list_item = new List<DAL.Booking>();
var qry = (from b in edc.Bookings
join cu in edc.Customers on b.customer_ref equals cu.customer_ref
join loc in edc.Locations on cu.customer_ref equals loc.customer_ref
join pl in edc.Pallets on i.booking_ref equals pl.booking_id
join pp in edc.ProductsToPallets on pl.PalletID equals pp.palletID
join pr in edc.Products on pp.productID equals pr.product_id
select b);
if (_booking != Null)
{
qry = qry.Where(b => b.booking_ref == _booking);
}
if (_project != Null)
{
qry = qry.Where(b => b.project_ref == _project);
}
if (_customer != Null)
{
qry = qry.Where(b => b.customer_ref == _customer);
}
if (_location != Null)
{
//add WHERE for table loc
}
if (_supplierSKU != Null)
{
//add WHERE for table pr
}
if (_eisSKU != Null)
{
//add WHERE for table pr
}
if (_assetREF != Null)
{
//add WHERE for table pp
}
list_item = qry.ToList();
return list_item;
}
由于
答案 0 :(得分:2)
你可以这样做:
var bQuery = edc.Bookings;
var quQuery = edc.Customers;
var locQuery = edc.Locations;
...
var prQuery = edc.Products;
if (_booking != Null)
{
bQuery = bQuery.Where(i => i.booking_ref == _booking);
}
if (_project != Null)
{
prQuery = prQuery.Where(i => i.project_ref == _project);
}
...
var list_item = (from b in bQuery
join cu in cuQuery on b.customer_ref equals cu.customer_ref
join loc in locQuery on cu.customer_ref equals loc.customer_ref
...
join pr in prQuery.Products on pp.productID equals pr.product_id
select b).ToList();
我们为所有已连接的表创建查询,但不执行它。然后我们添加过滤器表达式,然后通过连接之前形成的所有查询并实现最终查询到列表来形成最终查询。