简体   繁体   中英

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. I want to select the first photo that is associated with each InspirationID. I know that I will likely need to loop through the Photos table and then select 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
        )
    )
}).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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