2009-08-27 29 views
1

我有以下兩個表:亞音速3和LINQ集團通過與伯爵

Customer 
{ 
int Id 
int Name 
} 

Bills 
{ 
int Id 
int CustomerId 
decimal Amount 
bool IsDue 
} 

現在我試圖讓一個列表,其中我有:

  1. 一種與每一位客戶進入相關賬單計數。
  2. 每個客戶的條目與IsDue爲真的相關賬單計數。

我想這樣做的第一個這樣的:

var results = from c in _db.Customers 
       join b in _db.Bills on c.Id equals b.CustomerId into j1 
       from j2 in j1 
       group j2 by c.Id into grouped 
       select new 
        { 
         CustomerId = grouped.Key, 
         NoOfBills = grouped.Count() 
        }; 

這被投擲錯誤: 類型中的表達 'System.Collections.Generic.IEnumerable 1[OutstandingMonitor.MonitorData.Customer]' cannot be used for parameter of type 'System.Linq.IQueryable 1 [OutstandingMonitor.MonitorData.Customer]' ...

請幫我解決這個問題。

此外,這兩個查詢可以結合?

PS:不過使用亞音速3.0.0.3用ActiveRecord

回答

1

我發現了一個不那麼有效的解決方案(如果它確實有效,我會很想知道...:P)。這裏是:

var results = from d in _db.Bills 
      group d by d.CustomerId into g 
      select new 
      { 
       CustomerId = g.Key, 
       NoOfBills = g.Count() 
      }; 

var results2 = from c in _db.Customers 
      join r in results on c.Id equals r.CustomerId 
      select new 
      { 
       CustomerId = r.CustomerId, 
       CustomerName = c.Name, 
       City = c.City, 
       NoOfBills = r.NoOfBills 
      }; 

暫時工作正常。

0

無論你正在使用的價值「客戶的賬單相關的數」,不能你只要做到這一點的LINQ(這隻會工作,如果你在DBML建立適當的關係):

var customers = _db.Customers; // Not necessary, but here for clarity 

// ... more code 

// Access the number of bills for each customer: 

foreach (var customer in customers) 
{ 
    int totalBills = customers.Bills.Count(); 
    int totalDueBills customers.Bills.Where(b => b.IsDue).Count(); 
} 
+0

我認爲你指的是LINQ to SQL,他使用的是SubSonic。 –

+0

是的。我正在使用SQLite。有沒有什麼辦法與SubSonic和SQLite產生外鍵關係? – Yogesh

+0

@John - 對,我很抱歉假設LINQ到SQL,儘管我很驚訝類似的東西無法完成。 – Keith