2016-11-23 71 views
2

我試圖用Entity Framework來完成似乎很簡單的任務。我有2個微小的SQL表:Customers (Id, Name)Orders (Id, CustomerId, DateTime)。我需要從DB獲取數據,併爲每個客戶顯示一張包含所有客戶和前10位訂單(或者如果客戶少於10位的所有客戶)的表格。使用Entity Framework加入2個表並檢索table1中每個記錄的table2中的前X個記錄

很明顯如何獲取所需數據的簡單方法:讓所有的客戶在1個查詢(var customers = dc.Customers.ToList()),,然後作出foreach循環來檢索每個客戶訂單:

var dic = new Dictionary<Customer, List<Order>>(); 
foreach (var customer in customers) 
{ 
    dic.Add(customer, dc.Orders.Where(o => o.CustomerId == customer.Id).OrderBy(o => o.DateTime).Take(10).ToList(); 
} 

不過這樣一來使用了過多的DB查詢。如何只用1查詢數據庫達到同樣的效果?

回答

1

您可以使用

Dictionary<Customers, List<Orders>> dic = dc.Customers.Join(dc.Orders.OrderBy(o => o.DateTime).Take(10), 
          c => c.Id, 
          o => o.CustomerId, 
          (c, o) => new { Customers = c, Orders = o } 
          ) 
          .GroupBy(x => x.Customers) 
          .ToDictionary(x => x.Key, x => x.Select(y=>y.Orders) 

                  .ToList()); 

左連接

Dictionary<Customers, List<Orders>> dic = (from c in Customers 
                 join o in Orders.OrderBy(o => o.DateTime).Take(10) on c.Id equals o.CustomerId into j1 
                 from j2 in j1.DefaultIfEmpty() 
                 group j2 by c into grouped 
                 select new { Customers = grouped.Key, Orders = grouped.ToList() }) 
                .ToDictionary(x => x.Customers, x => x.Orders); 
+0

這是否做了一個左連接? –

+0

我正在看生成的SQL,它似乎提取所有連接的記錄,而不是前10名。有沒有辦法提取數據庫端的TOP 10,而不是在客戶端? –

+0

我更新了我的答案。現在前數據加入前十位 – Eldeniz

相關問題