這是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。 –