![](/img/trans.png)
[英]Need help with LINQ query that joins two tables containing periodic events
[英]Simple Linq query that joins two tables and returns a collection
我有两个表LookUpCodes和LookUpValues,它们的定义如下:
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
在上面的代码段中,我们将listA
的内容与listA
的内容连接listB
并且我们的join
基于两个列表项中都存在的commonId
属性。 显然,满足join
条件的a
和b
对将形成可能的许多结果之一。
然后将where
子句应用于联接的结果join. The joined items that pass the
join. The joined items that pass the
where filter is the new result. Even at this point the results is still pairs of
join. The joined items that pass the
filter is the new result. Even at this point the results is still pairs of
filter is the new result. Even at this point the results is still pairs of
a and
b`对。
最后一个项目,使用select
关键字将每对结果复制到一个新对象。 对于您的情况,对于还通过where
过滤器的每对code
和values
,您仅返回values
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.