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 回答