1

Linq to Entities の左外部結合カウントを理解できません。

私のクエリは次のとおりです。

SELECT Locations.LocationId, Locations.LocationName, LocationPrizes.PrizeId, LocationPrizes.PrizeQuantity, Prizes.PrizeName, ISNULL(COUNT(WonPrizes.WonPrizeId), 0) AS WonPrizes 

FROM Locations 

INNER JOIN LocationPrizes ON Locations.LocationId = LocationPrizes.LocationId INNER JOIN Prizes ON LocationPrizes.PrizeId = Prizes.PrizeId 

LEFT OUTER JOIN WonPrizes ON Locations.LocationId = WonPrizes.LocationId AND Prizes.PrizeId = WonPrizes.PrizeId

GROUP BY Locations.LocationId, Locations.LocationName, LocationPrizes.PrizeId, LocationPrizes.PrizeQuantity, Prizes.PrizeName

私のLinqは:

var locationPrizes = from l in context.Locations
                       select new
                           {
                               l.LocationId,
                               l.LocationName,
                               Prizes = from o in l.LocationPrizes
                                        select new
                                            {
                                                o.PrizeId,
                                                o.PrizeQuantity,
                                                o.Prize.PrizeJson
                                            }
                           };

左外部結合部分が正しく機能しているとカウントできません。ポインタはありますか?

4

1 に答える 1

3

LocationPrizes -> WonPrizes からの関連付けがある場合は、次のようにすることができます。

var locationPrizes = 
    from l in context.Locations
    select new
    {
        l.LocationId,
        l.LocationName,
        Prizes = 
            from o in l.LocationPrizes 
            select new
            {
                o.PrizeId,
                o.PrizeQuantity,
                o.Prize.PrizeJson
                WonPrizes = o.WonPrizes.Count();
            }
    };

そうでない場合、これも機能します(以下のマイナーな編集で機能します):

var locationPrizes = 
    from l in context.Locations
    select new
    {
        l.LocationId,
        l.LocationName,
        Prizes = 
            from o in l.LocationPrizes 
            select new
            {
                o.PrizeId,
                o.PrizeQuantity,
                o.Prize.PrizeJson
                WonPrizes = 
                    (from w in context.WonPrizes
                     where w.PrizeId == o.PrizeId 
                        && w.LocationId == l.LocationId
                     select w)
                    .Count()
            }
    };
于 2013-03-09T19:24:41.940 に答える