tags:

views:

57

answers:

2

Hey, having some problems figuring this one out.

select *,(select top 1 chicken_nr from chicken_photo where chicken = code order by [sort]) as Photo from Chicken

Code is a column in Table Chicken

Basically getting the cover photo for this chicken.

To make it clearer, I want it to return multiple rows from table Chicken. But only a single entry from chicken_photo.

var q = from chicken in data.chickens
                    join photos in data.chicken_photos
                    on chicken.Code equals photos.chicken                    
                    where chicken.Lang==lang && chicken.photographer_nr == nr
                    group chicken by new     {chicken.photographer,photos.Photograph_Nr,chicken.Title,chicken.Code}              
A: 
var photo = (from c in chicken_photo where c.code = chicken orderby c.sort select c.chicken_nr).Take(1).SingleOrDefault();

You should really flesh out your question more...

Matthew Abbott
Hmm, I want multiple chickens, so I get multiple rows, but only retrieving one entry from chicken_photo
Exception Duck
+1  A: 

I figured it out.

Pretty obvious actually, too obvious :)

var q = from chicken in data.chickens
                where chicken.photographer_nr == nr && lang == chicken.Lang
                select new { chicken.photographer, chicken.Code, chicken.Title,Photo = (from b in data.chicken_photos where b.chicken==chicken.Code orderby b.Sort select b.Photograph_Nr).FirstOrDefault() };
Exception Duck
Take(1) is redundant. First() will return the first value in the sequence, whether that sequence contains one or more values. Note that it will throw if there there are no photos, use FirstOrDefault() if you want to avoid this.
jeroenh
Thanks, I updated the answer to reflect this better practice, although in my case photos is always populated
Exception Duck
Not sure about if this is good coding though, if the query is returning 100 entries, that means 100 connections to the database for the select top 1Stored procedures is probably the way to go here.
Exception Duck