This is the SQL query I am trying to convert into a LINQ query:
SELECT
ContactID,
COUNT (ls.SoldToContactID) AS Count
FROM
Contacts c
LEFT OUTER JOIN LeadSales ls on c.ContactID = ls.SoldToContactID
GROUP BY
c.ContactID
I'm getting the results expected from leadSales
, but I am not picking up any of the rows from contacts
that have no match in leadSales
.
var leadSales = (IQueryable of the LeadSales table)
var contacts = (IQueryable of the Contacts table)
BuyerList = from ls in leadSales
join contact in contacts on ls.SoldToContactID equals contact.ContactID into sb
from subBuyer in sb.DefaultIfEmpty()
group ls by new {
subBuyer.ContactID,
FirstName = subBuyer.FirstName,
LastName = subBuyer.LastName
} into g
select new LeadBuyersByStateItem
{
ContactID = g.Key.ContactID,
Name = g.Key.LastName + ", " + g.Key.FirstName,
LeadsCount = g.Count()
};
EDIT:
Based on feedback from Ivan, I now have this:
BuyerList = from contact in contacts
join ls in leadSales on contact.ContactID equals ls.SoldToContactID into c_ls
from ls in c_ls.DefaultIfEmpty()
group contact by new
{
ls.Contact.ContactID,
FirstName = ls.Contact.FirstName,
LastName = ls.Contact.LastName
} into g
select new LeadBuyersByStateItem
{
ContactID = g.Key.ContactID,
Name = g.Key.LastName + ", " + g.Key.FirstName,
LeadsCount = g.Count()
};
But, this is throwing this error:
The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.