2014-01-27 63 views
1

我的模式是這樣的:使用加入,集團通過和SUM在實體框架

public class ReturnItem 
{ 
    public int returnItemId { get ; set; } 
    public int returnRequestId { get; set; } 
    public int quantity { get; set; } 
    public string item { get; set; } 
} 

public class ReturnRequest 
{ 
    public int returnRequestId { get; set; } 
    public string orderNumber { get; set; } 
    public IEnumerable<ReturnItem> returnItems { get; set; } 
} 

而且我有以下查詢:

SELECT item, sum(quantity) 
FROM ReturnItem 
JOIN ReturnRequest 
ON ReturnRequest.returnRequestId = ReturnItem.returnRequestId 
WHERE ReturnRequest.orderNumber = '1XX' 
GROUP BY item 

如何查詢轉換爲實體框架和返回List<ReturnItem>?我可以使用.Include而不是.Join嗎?

回答

7
from ri in db.ReturnItems 
join rr in db.ReturnRequests 
    on ri.returnRequestId equals rr.returnRequestId 
where rr.orderNumber == "1XX" 
group ri by ri.item into g 
select new { 
    Item = g.Key, 
    Quantity = g.Sum(i => i.quantity) 
} 

不能使用Include代替Join因爲Include翻譯成左外連接但你需要內加入這裏。

但是你可以使用導航屬性來執行加入隱含:

db.ReturnRequests 
    .Where(rr => rr.orderNumber == "1XX") 
    .SelectMany(rr => rr.returnItems) 
    .GroupBy(ri => ri.item) 
    .Select(g => new { 
     Item = g.Key, 
     Quantity = g.Sum(ri => ri.quantity) 
    }); 
+0

如何從該查詢返回一個列表''? – janinaj

+0

@janinaj你的SQL查詢返回不同的結果。但是你可以選擇'new ReturnItem {item = g.Key,quantity = g.Sum(i => i.quantity)}'而不是匿名對象。轉換爲列表非常簡單我認爲 –

+0

嗨,我收到錯誤'指定的類型成員'returnItems'不支持LINQ to Entities。只支持初始化器,實體成員和實體導航屬性。' – janinaj