Translate SQL query to LINQ
THIS USER HAS ALREADY AS开发者_如何学CKED THE EXACT DUPLICATE A FEW MINUTES AGO sql and linq query
PhotoAlbums
table
Photos
table:
SELECT AlbumID, Title, Date,
(SELECT TOP (1) PhotoID
FROM Photos AS c
WHERE (AlbumID = a.AlbumID)) AS PhotoID
FROM PhotoAlbums AS a
I need this query written in LINQ-to-SQL. Thanks in advance
You can do it like this:
var result =
yourContext.PhotoAlbums.Select(a =>
new {a.AlbumId, a.Title, a.Date, a.Photos.First().PhotoId }
);
Also, LinqPad is a very nice tool, that can help you do this.
Assuming that you have defined a relationship between PhotoAlbums
and Photos
in your DBML file, you can do this:
var albums = dataContext.PhotoAlbums.Select(album => new {
AlbumId = album.AlbumId,
Title = album.Title
Date = album.Date,
PhotoId = album.Photos.Select(photo => photo.PhotoId).FirstOrDefault()
});
精彩评论