2016-12-04 23 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

谢谢你的教育。我希望这也可以帮助其他人。 –