I have this simple piece of sql that does exactly what I need…
SELECT MIN(pb.Id) AS Id, MIN(pb.Quantity) AS Requested, SUM(pbi.Quantity) AS Total
FROM PickBatchItems AS pb
LEFT JOIN PickBatchItemLocations AS pbi ON pb.Id = pbi.PickBatchItemId
GROUP BY pb.Id
Results in…
Id, Requested, Total
1 100 NULL
2 200 165
3 200 NULL
This is exactly what I want but I need this to be in Linq.
So far I have…
var pick = (from pb in db.PickItems
join pbi in db.PickItemLocations on pb.Id equals pbi.PickBatchItemId into TempJoin
from resList in TempJoin.DefaultIfEmpty()
where pb.Id == iPickItemId
group resList by pb.Id into g
select new
{
Id = g.Key,
RequestedQuantity = g.Min(???????????????????????),
SentQuantity = g.Sum(a => a.Quantity == null ? 0 : a.Quantity),
}).FirstOrDefault();
How can I get the RequestedQuantity?
UPDATE:
Thanks to ‘David B’ I have the answer:
var pick = (from pb in db.PickBatchItems
join pbi in db.PickBatchItemLocations on pb.Id equals pbi.PickBatchItemId into TempJoin
from resList in TempJoin.DefaultIfEmpty()
where pb.Id == iPickItemId
group new { PickItem = pb, PickItemLocation = resList } by pb.Id into g
select new
{
Id = g.Key,
RequestedQuantity = g.Min(a => a.PickItem.Quantity),
SentQuantity = g.Sum(a => a.PickItemLocation.Quantity == null ? 0 : a.PickItemLocation.Quantity),
}).FirstOrDefault();
This joins and returns my two tables even if the PickBatchItemLocations table is empty.
Assuming that PickItems.Id is the primary key, it seems that joining is the first step to a road that need not be traveled.
If you still want to take the long road, do this: