2012-02-17 299 views
2

我有一個SQL語句,我試圖轉換爲LINQ查詢。我需要這樣做,因爲我不能編輯我的數據庫:(無論如何,我有一個SQL語句如下所示:LINQ - 嵌套查詢

SELECT 
    CustomerID, 
    FirstName, 
    LastName, 
    Gender, 
    BirthMonth, 
    (SELECT COUNT(ID) FROM PurchaseOrder WHERE [CustomerID]=CustomerID) as TotalPurchases 
FROM 
    MyEntities 

我知道該怎麼做的一切在LINQ除外的嵌套查詢部分目前,我有以下幾點:?

var results = from x in context.MyEntities 
       select new Customer() 
       { 
       CustomerID = x.CustomerID, 
       FirstName = x.FirstName, 
       LastName = x.LastName, 
       Gender = x.Gender, 
       BirthMonth = x.BirthMonth, 
       TotalPurchases = ? 
       }; 

如何執行在LINQ嵌套查詢來獲取TotalPurchases值

謝謝你這麼多

回答

6

!你可以只嵌套的LINQ to Entities查詢,以及:

var results = from x in context.MyEntities 
       select new Customer() 
       { 
       CustomerID = x.CustomerID, 
       FirstName = x.FirstName, 
       LastName = x.LastName, 
       Gender = x.Gender, 
       BirthMonth = x.BirthMonth, 
       TotalPurchases = context.PurchaseOrders 
             .Where(po=>po.CustomerId == x.CustomerId) 
             .Count() 
       }; 
3

只是做一個報數「個PurchaseOrder」,我認爲是對客戶的實體的導航屬性的。

TotalPurchases = x.PurchaseOrders.Count() 
0

通過BrokenGlass答案使用LINQ到實體時,並導致錯誤,指出「無法創建類型‘myEntity所’的恆定值,並沒有爲我工作。只有基本類型或枚舉類型在這個支持語境「。

爲了克服這一點,我使用了以下內容:

var results = from x in context.MyEntities 
       join po in context.PurchaseOrders on x.CustomerID equals po.CustomerID into purchaseOrders 
       select new Customer() 
       { 
       CustomerID = x.CustomerID, 
       FirstName = x.FirstName, 
       LastName = x.LastName, 
       Gender = x.Gender, 
       BirthMonth = x.BirthMonth, 
       TotalPurchases = purchaseOrders.Count() 
       };