简体   繁体   中英

Not counting null values from a linq LEFT OUTER JOIN query

I have this sql query that does exactly what i want but i need it in linq. It returns a few AVC rows and counts how many PersonAVCPermission that has status 1 linked to it

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

I have this query in linq and it does the same thing except when there are no PersonAVCPermission it still counts 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)
        };

Im guessing that with DefaultIfEmpty() it places null rows in the list that then gets counted so i try to exclude them with (o => o.Id != null) but it still counts everything as at least one

If i dont use DefaultIfEmpty() it skips the rows with count 0 completely

How can i exclude them or am i doing it completely wrong?

How about using .Any() and a 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)
};

You don't need the join, nor the grouping:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM