Dies ist die SQL-Abfrage zu holen ich in einer LINQ-Abfrage zu konvertieren Ich versuche:Nicht immer LEFT Abfrage in LINQ JOIN leere Zeilen
SELECT
ContactID,
COUNT (ls.SoldToContactID) AS Count
FROM
Contacts c
LEFT OUTER JOIN LeadSales ls on c.ContactID = ls.SoldToContactID
GROUP BY
c.ContactID
ich die Ergebnisse von leadSales
erwartet bekommen, aber ich bin Keine der Zeilen von contacts
, die keine Übereinstimmung in leadSales
haben.
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:
Basierend auf dem Feedback von Ivan, ich das jetzt haben:
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()
};
Aber das diesen Fehler zu werfen:
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.
Sie geben nicht auf :) Ich könnte es zum dritten Mal schließen, weil es immer noch ein Duplikat von http://stackoverflow.com/questions/3404975/left-outer-join-in-linq ist. Stattdessen gebe ich Ihnen diesmal einen Hinweis: 'von c in Kontakte verbinden ls in leadSales auf c.ContactID gleich ls.SoldToContactID in c_ls von ls in c_ls.DefaultIfEmpty() ...'. Hoffe du kannst es von dort aus schaffen. –
Mögliches Duplikat von [LEFT OUTER JOIN in LINQ] (http: // stackoverflow.com/questions/3404975/left-outer-join-in-linq) – mrfreester
@Ivan, das hatte ich schon nach dem letzten Kommentar (beim zweiten Mal) ausprobiert. Schrauben Sie es. Ich werde nur das SQL verwenden und LINQ vergessen. –