2010-10-22 843 views
0

需要幫助在linq中完成。Linq in C#需要查詢 - 一對多關係,需要一對多記錄

我有3張桌子。

  1. 客戶

  2. CustumerOrder

  3. 訂單明細

我需要在一個查詢中的所有客戶列表(前提是他們已經把ATLEAST一個順序)的所有訂單僅當訂單價值高於100時才爲每位客戶訂購。

問候,

惡劣

+2

請添加比表名更多的細節。例如,列。更好的是,因爲這是LinqToSql,請改爲提供您的類/屬性名稱。 – 2010-10-22 18:57:55

+0

嗨Kirk,可以說有以下列 - 1.客戶 - 客戶Id,客戶名稱2.客戶訂單 - OrderId,CutomerId,OrderAmount 3. OrderDetails - OrderId,OrderDate ......現在請讓我知道如何獲得收集像Dictionary >使用Linq查詢.......希望這很好解釋。這只是常見的客戶訂單情景,您可以根據情景假設其他細節。 – 2010-10-23 09:09:53

回答

0

我說你想是這樣的:

from c in Customers 
where c.CustomerOrders.Any() 
select new 
{ 
    customer, 
    Orders = 
    from co in c.CustomerOrders 
    where co.TotalPrice > 100 
    select co.OrderDetails 
} 

或者,如果你不在CustomerOrder表中沒有「TotalPrice」列,請用以下內容替換內部查詢:

Orders = 
    from cp in c.CustomerOrders 
    where co.OrderDetails.Sum (od => od.Price) > 100 
    select co.OrderDetails 

編輯:如果你想與OrderTotalPrice 100多家,包括客戶只與至少一個訂單,使用聲明:

from c in Customers 
let highValueOrders = 
    from co in c.CustomerOrders 
    where co.TotalPrice > 100 
    select co.OrderDetails 
where highValueOrders.Any() 
select new 
{ 
    customer, 
    highValueOrders 
} 

您可以用類似的方式添加更多的條件。

+0

非常感謝大家。我非常感謝快速回復。 但此查詢不考慮該部分 - 客戶將是最終名單隻有當他有ATLEAST一個爲了與OrderTotalPrice超過100 + 其實我有幾個條件,這裏列入客戶的最終選擇 - 如果客戶的類型爲「常規」客戶,或者年齡> 35,如果客戶的類型爲「稀有」,則只有至少有一個訂單的年齡> 30時才選擇客戶。 CustomerType存儲在CustomerDetails表中。 請幫我這個.. 問候, Harshal – 2010-10-23 07:17:44

+0

非常感謝喬..幾個問題 - 1,我們可以調用LINQ查詢或Lambda表達式內C#的功能呢?我需要這個來計算年齡,在我的數據庫中有一個生日字段,我需要從這個字段計算年齡2.我如何從上面的LINQ查詢獲取列表,現在我只需要從上面的查詢客戶有更多的行數woth客戶詳細信息。我真的很困惑。不知道我怎麼能通過這個UI。我可以得到像Dictionary >的東西嗎? – 2010-10-23 09:04:35

+0

你不能在通過L2S或EF管道的lambda表達式中調用你自己的函數。有關解決方法,請查看:http://mathgeekcoder.blogspot.com/2008/07/advanced-domain-model-queries-using.html – 2010-10-24 01:28:57

0

下面是根據了一些假設一個猜測:

var result = 
    from customer in Customers.Where(a => a.CustomerOrder.Count > 0) 
    from order in CustomerOrder.Where(a => a.OrderDetails.Sum(b => b.Price) > 100) 
    select new 
    { 
     customer, 
     order.OrderDetails 
    }