2015-09-18 179 views
0

我正在尋找如何過濾下面的LINQ查詢的建議。 您可以看到涉及6個表格,從中選擇的表格是b - 預訂。 然後,根據傳入的變量是否爲null,我添加WHERE子句,但據我瞭解,如果我從b中選擇,那麼我只能將WHERE子句添加到b,所以如果我想添加一個WHERE到任何其他連接的表我怎麼能在LINQ中做到這一點?多表LINQ查詢中的WHERE子句

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

你有沒有試過,例如'qry = qry.Where(i => loc.something == value);'? – Jamiec

+0

是的,intellisense只提供字段b – DarkW1nter

+0

啊,是的,現在我明白了 - 因爲'select b' – Jamiec

回答

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

我們構成了所有連接的表的查詢,但不執行它。然後我們添加過濾器表達式,然後通過連接之前形成的所有查詢並將最終查詢實現爲列表來形成最終查詢。

+0

謝謝,直到今天晚些時候纔會嘗試這樣做,所以會給予更新 – DarkW1nter