我有兩個表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();
}
感謝您的及時迴應和真正的好解釋。我還有一個問題,我如何按照CodeValue屬性的降序排列值? –
不客氣。你可以做到這一點,就像你已經描述過的那樣簡單。就在select語句放置這個'orderby values descending' – Christos
謝謝你的教育。我希望這也可以幫助其他人。 –