这是SQL查询我想转换成LINQ查询:没有得到LEFT JOIN在LINQ查询拿起空行
SELECT
ContactID,
COUNT (ls.SoldToContactID) AS Count
FROM
Contacts c
LEFT OUTER JOIN LeadSales ls on c.ContactID = ls.SoldToContactID
GROUP BY
c.ContactID
我碰到leadSales
预期的结果,但我不从contacts
中挑选出在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()
};
编辑:基于从伊万反馈
,我现在有这样的:
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()
};
但是,这是引发此错误:
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.
你不会放弃:)我可以第三次关闭它,因为它仍然是http://stackoverflow.com/questions/3404975/left-outer-join-in-linq的重复。相反,这次我给你一个提示:'从c中的联系人加入ls到leadSales上的c.ContactID等于ls.SoldToContactID到ls中的c_ls中c_ls.DefaultIfEmpty()...'。希望你可以从那里管理它。 –
[LINQ中的LEFT OUTER JOIN](http:// stackoverflow。com/questions/3404975/left-outer-join-in-linq) – mrfreester
@Ivan,我已经在你最后的评论(第二次)之后尝试过了。算了。我只是要使用SQL并忘记了LINQ。 –