简单的Linq查询联接两个表,并返回一个集合
问题描述:
我有两个表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();
}
答
你很接近你正在寻找:
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
。显然,符合a
和b
的这一对将满足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
过滤器的每对code
和values
,只返回values
。
感谢您的及时回应和真正的好解释。我还有一个问题,我如何按照CodeValue属性的降序排列值? –
不客气。你可以做到这一点,就像你已经描述过的那样简单。就在select语句放置这个'orderby values descending' – Christos
谢谢你的教育。我希望这也可以帮助其他人。 –