开发者

Translate SQL query to LINQ

THIS USER HAS ALREADY AS开发者_如何学CKED THE EXACT DUPLICATE A FEW MINUTES AGO sql and linq query

PhotoAlbums table

AlbumID

Title

Date

Photos table:

PhotoID

Title

Date

AlbumID

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()
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜