Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have two tables: Album(AlbumId, AlbumName) and Photo(PhotoId, PhotoName, AlbumId)

I have :

 select top 1 Photo.PhotoId
 from Photo
 where Album.AlbumId=Photo.AlbumId
 order by NEWID()

This is return one record random

I want convert it to Linq to sql. I tried but not success.

share|improve this question
what you tried? – Manish Mishra 20 hours ago
yes.I was tried.I begin study for Linq.Please help me! – user2465772 20 hours ago
you need to use linq join. – Manish Mishra 20 hours ago
Please show what you tried. Then we know what "not success" means. – Gert Arnold 18 hours ago

2 Answers

I believe you would need to join the tables. Also, it depends on what language you are using when you want to create a random Guid - my example uses C#. In query syntax, it should be something like:

from p in Photo
join a in Album on a.AlbumId equals p.AlbumId
orderby Guid.NewGuid()
take 1
select p.PhotoId
share|improve this answer

try this:

var photoId = ( from photo in collecPhotos
                join album in collecAlbums on photo.AlbumId equals album.AlbumId
                orderby NEWID()
                select photo.PhotoId).First();

where collecPhotos and collecAlbums are the collection of your Photo and Album entity i.e. data from the tables. so it can also be myDbContext.Photos and myDbContext.Albums where myDbContext is your Linq-to-Sql DataContext.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.