简体   繁体   English

LINQ:从表A中选择第一项,该表在链接到表B的链接表中具有相应的ID

[英]LINQ: Select First Item from Table A that has corresponding ID in linking table that connects to Table B

I currently have an 'Inspirations' table with ID, Name, and Description, a 'Photos' table with ID, Name, and Description, and a linking table InspirationPhotos that just has the foreign keys of PhotoID and InspirationID. 我目前有一个具有ID,名称和描述的'Inspirations'表,一个具有ID,名称和描述的'Photos'表以及一个链接表InspirationPhotos,该表仅具有PhotoID和InspirationID的外键。 I want to select the first photo that is associated with each InspirationID. 我想选择与每个InspirationID相关联的第一张照片。 I know that I will likely need to loop through the Photos table and then select FirstOrDefault. 我知道我可能需要遍历“照片”表,然后选择“ FirstOrDefault”。

I think I will need something like 我想我需要类似的东西

foreach (var inspiration in Inspirations)
{
    inspiration.Photos.Where(x=>x.PhotoId == ?)
}

Maybe I should add a primary key to the linking table? 也许我应该在链接表中添加主键? Thanks in advance 提前致谢

You can do it like this: 您可以这样做:

var inspirationPhotos = db.Inspirations.Select(i => new {
    Inspiration = i
,   Photo = db.Photos.FirstOrDefault(p =>
        db.InspirationPhotos.Any(ip =>
            ip.PhotoId == p.Id && ip.InspirationId == i.Id
        )
    )
}).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM