2016-12-04 35 views
0

我有兩個表LookUpCodes和LookUpValues它們被定義如下:簡單的Linq查詢聯接兩個表,並返回一個集合

public partial class LookUpCodes 
{ 
    public int Id { get; set; } 
    public int? CodeId { get; set; } 
    public string Code { get; set; } 
    public string Description { get; set; } 
} 



public partial class LookUpValues 
{ 
    public int Id { get; set; } 
    public int CodeId { get; set; } 
    public string CodeValue { get; set; } 
    public bool? IsActive { get; set; } 
} 

每個LookUpCode可以有多個與之相關的值。我想傳入一個代碼並獲取關聯的值列表。

這可能是一個常見的問題,因爲我已經在任何地方看到了這個問題,如果有人可以解釋如何構建正確的查詢,我不會尋求答案本身。

這是我迄今所做的:

public IEnumerable<LookUpValues> GetValuesByCode(string cd) 
{ 
    var query = from code in _context.LookUpCodes 
       join values in _context.LookUpValues on code.CodeId equals values.CodeId 
       where code.Code == cd 
       select new { LookUpValues = values }; 
    return (IEnumerable<LookUpValues>) query.ToList(); 
} 

回答

0

你很接近你正在尋找:

public IEnumerable<LookUpValues> GetValuesByCode(string cd) 
{ 
    var query = from code in _context.LookUpCodes 
       join values in _context.LookUpValues 
       on code.CodeId equals values.CodeId 
       where code.Code == cd 
       select values; 

    return query; 
} 

既然你已經寫了join,我假設你有了解它是如何工作的。然而,讓我們重新審視它:

from a in listA 
join b in listB 
on a.commonId equals b.commonId 

在我們與listB內容加入的listA上面的內容片斷,我們在commonId財產存在於兩個列表中的項目基地,他們join。顯然,符合ab的這一對將滿足join的標準,它將構成可能的許多結果之一。

然後where子句適用於join. The joined items that pass the的結果,其中filter is the new result. Even at this point the results is still pairs of a and b`。

最後你的項目,使用關鍵字select每一對結果到一個新的對象。在你的情況下,對於通過where過濾器的每對codevalues,只返回values

+0

感謝您的及時迴應和真正的好解釋。我還有一個問題,我如何按照CodeValue屬性的降序排列值? –

+0

不客氣。你可以做到這一點,就像你已經描述過的那樣簡單。就在select語句放置這個'orderby values descending' – Christos

+0

謝謝你的教育。我希望這也可以幫助其他人。 –