不计算linq LEFT OUTER JOIN查询中的空值

时间:2013-10-25 10:59:10

标签: c# sql linq

我有这个SQL查询,它完全符合我的要求,但我需要它在linq。它返回一些AVC行并计算有多少个状态为1的PersonAVCPermission链接到它

SELECT a.Id, a.Name, a.Address, COUNT(p.AVCID) AS Count
FROM AVC AS a
LEFT OUTER JOIN 
(
    SELECT PersonAVCPermission.AVCId
    FROM PersonAVCPermission
    WHERE PersonAVCPermission.Status = 1
) AS p 
ON a.Id = p.AVCId
GROUP BY a.Id, a.Name, a.Address

我在linq中有这个查询并且它做同样的事情,除非没有PersonAVCPermission它仍然计数1

var yellows = odc.PersonAVCPermissions.Where(o => o.Status == (int)AVCStatus.Yellow);

var q = from a in odc.AVCs
        from p in yellows.Where(o => o.AVCId == a.Id).DefaultIfEmpty()
        group a by new { a.Id, a.Name, a.Address } into agroup
        select new AVCListItem
        {
            Id = agroup.Key.Id,
            Name = agroup.Key.Name,
            Address = agroup.Key.Address,
            Count = agroup.Count(o => o.Id != null)
        };

我猜测使用DefaultIfEmpty()它会在列表中放置空行然后计算,所以我尝试用(o =&gt; o.Id!= null)排除它们但它仍然将所有内容都算作至少一个< / p>

如果我不使用DefaultIfEmpty(),它会完全跳过计数为0的行

我如何排除它们或者我完全错了?

2 个答案:

答案 0 :(得分:1)

如何使用.Any()和Let?

var yellows = odc.PersonAVCPermissions.Where(o => o.Status == (int)AVCStatus.Yellow);

var q = from a in odc.AVCs
let Y = (from p in yellows.Where(o => o.AVCId == a.Id) select p).Any()
where Y == true
group a by new { a.Id, a.Name, a.Address } into agroup
select new AVCListItem
{
    Id = agroup.Key.Id,
    Name = agroup.Key.Name,
    Address = agroup.Key.Address,
    Count = agroup.Count(o => o.Id != null)
};

答案 1 :(得分:0)

您不需要加入,也不需要分组:

var q = from a in odc.AVCs
        select new AVCListItem
        {
            Id = a.Id,
            Name = a.Name,
            Address = a.Address,
            Count = yellows.Where(o => o.AVCId == a.Id).Count()
        };