Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities three table join query

I'm having a bit trouble with a query in Linq to Entities which I hope someone can shed a light on :-) What I'm trying to do is to create a query that joins three tables.

So far it works, but since the last table I'm trying to join is empty, the result of the query doesn't contain any records. When I remove the last join, it gives me the right results.

My query looks like this:

var query = from p in db.QuizParticipants
            join points in db.ParticipantPoints on p.id 
            equals points.participantId into participantsGroup
            from po in participantsGroup
            join winners in db.Winners on p.id 
            equals winners.participantId into winnersGroup
            from w in winnersGroup
            where p.hasAttended == 1 && p.weeknumber == weeknumber
            select new
            {
                ParticipantId = p.id,
                HasAttended = p.hasAttended,
                Weeknumber = p.weeknumber, 
                UmbracoMemberId = p.umbMemberId,
                Points = po.points,
                HasWonFirstPrize = w.hasWonFirstPrize,
                HasWonVoucher = w.hasWonVoucher                                    
            };

What I would like is to get some records even if the Winners table is empty or there is no match in it.

Any help/hint on this is greatly appreciated! :-)

Thanks a lot in advance.

/ Bo

like image 541
bomortensen Avatar asked Jan 16 '12 19:01

bomortensen


2 Answers

If you set these up as related entities instead of doing joins, I think it will be easier to do what you're trying to do.

var query = from p in db.QuizParticipants
            where p.hasAttended == 1 && p.weeknumber == weeknumber
            select new
            {
                ParticipantId = p.id,
                HasAttended = p.hasAttended,
                Weeknumber = p.weeknumber, 
                UmbracoMemberId = p.umbMemberId,
                Points = p.ParticipantPoints.Sum(pts => pts.points),
                HasWonFirstPrize = p.Winners.Any(w => w.hasWonFirstPrize),
                HasWonVoucher = p.Winners.Any(w => w.hasWonVoucher)
            };

This is assuming hasWonFirstPrize and hasWonVoucher are boolean fields, but you can use any aggregate function to get the results you need, such as p.Winners.Any(w => w.hasWonFirstPrize == 1)

like image 100
Joel C Avatar answered Nov 12 '22 11:11

Joel C


I don't use query syntax a lot but I believe you need to change from w in winnersGroup to from w in winnersGroup.DefaultIfEmpty()

like image 43
cadrell0 Avatar answered Nov 12 '22 12:11

cadrell0