views:

47

answers:

2

THIS USER HAS ALREADY ASKED THE EXACT DUPLICATE A FEW MINUTES AGO http://stackoverflow.com/questions/2552190/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

+2  A: 

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()
});
Mark Byers
Nice, thank you!
ile
+3  A: 

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.

klausbyskov
+1 for linqpad reference.
amelvin