2012-07-26 43 views
0

在一個應用程序中,我需要顯示客戶,產品的編號(計數) {從此處插入其他實體} db.Custmers,db.Products等)每個狀態(來自db.Geodata)。通過查詢集成多個組(將一個表與其他各種數據結合並計數匹配)

一個結果可能看起來像

Customers: { Status = "OK", Count = 59 } 
      { Status = "INVALID", Count = 14 } 
      { Status = "NO_RESULT", Count = 29 } 

Products: { Status = "OK", Count = 541 } 
      { Status = "INVALID", Count = 33 } 
      { Status = "NO_RESULT", Count = 42 } 

所以我寫了一個查詢....

from customer in db.Kunden 
join pin in db.Geodata 
    on customer.AdressNr equals pin.AdressNr 
group customer by pin.Status 
into groups 
select new {Status = groups.Key, Count = groups.Count()}; 

,另一個....

from product in db.Products 
join pin in db.Geodata 
    on product.AdressNr equals pin.AdressNr 
group product by pin.Status 
into groups 
select new {Status = groups.Key, Count = groups.Count()}; 

還有更多。他們工作得很好。但我努力將它們全部集成到一個查詢中(從而整合了重複的部分,即最後兩行)。

我該如何做到這一點?

編輯:任何人都可以幫助我改善這個問題嗎?是否缺少關鍵信息?這是太局部還是太寬?

回答

0

即使現在可能已經太晚了,它可能會幫助你。

LINQ並沒有被設計用來構建像SQL這樣的語句,你可能會使用StringBuilder或類似的東西。

LINQ優於SQL的優點是在編碼時有編譯時檢查。在SQL中,您必須運行您的代碼並嘗試執行&錯誤。

但是,我發現了一個類似的問題,在您的問題發出之後的5個月內被問到/回答了:https://stackoverflow.com/a/13797168

採用這個方法,你可以有類似以下內容:

public object[] GetCustomers() 
{ 
    return GetEntityCount("Customers"); 
} 

private object[] GetEntityCount(string entityName) 
{ 
    return (from obj in GetSpecificEntity(entityName) join pin ...).ToArray(); 
} 

private IEnumerable GetSpecificEntity(string entityName) 
{ 
    switch (entityName) 
    { 
     case "Customers": return db.Customers; 
    } 
} 
相關問題