bomortensen
bomortensen

Reputation: 3396

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

Upvotes: 5

Views: 4411

Answers (2)

Joel C
Joel C

Reputation: 5567

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)

Upvotes: 5

cadrell0
cadrell0

Reputation: 17307

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()

Upvotes: 4

Related Questions