簡體   English   中英

Linq to Entities Left Outer Join with不同類型

[英]Linq to Entities Left Outer Join with different types

到目前為止,我可能已經在這個問題上花費了40個小時,我已經在該網站和google上嘗試了所有解決方案,但仍然無法完成這項工作。

我需要將表保留到存儲在var中的上一個查詢的結果中。 join字段是要查詢var中結果的表中的varchar,以及要連接的表中的bigint(長整數)。 這是當前的嘗試,它告訴我“對象引用未設置為對象的實例”。 所有Entities錯誤似乎都是胡說八道,對我來說是謊言,我想這是在告訴我什么都沒有,但誰知道。

        List<reportUser> ru = leaders
        .GroupJoin(db.sweeps,
        a => a.FBID.ToString(),
        s => s.userFBID.First().ToString(),
        (a, matching) => new reportUser
        {
            FBID = a.FBID,
            CurrentPoints = a.CurrentPoints,
            Name = matching.FirstOrDefault().Name,
            Email = matching.FirstOrDefault().email
        }
        ?? new reportUser
        {
            FBID = 0,
            CurrentPoints = 0,
            Name = "",
            Email = ""
        })
        .Select(a => a)
        .ToList();

這是下面要求的SQL。 我還包括了用於構建Leaders對象的SQL,以上所有內容實際上是要表示的是最后一行,這只是左聯接。

從(選擇a.userfbid,從(選擇userfbid,pointvalue)得分中整體選擇s.name,s.email,b.score,c.score從l左聯接qa.id = l.qaid的qa q.id = qa.qid上的左連接q qq.id = q.qzid上的左連接qz其中qa.pointvalue> 0和qz.cid = 12 Union都選擇fbid userfbid,從bn的pointvalue選擇date> ='5 / 9/2011 04:00'和date <='5/16/2011 04:00')由a.userfbid分組

左聯接(選擇a.userfbid,sum(a.pointvalue)分數來自(選擇l用戶聯結,pointvalue從l左聯接qa在qa.id = l.qaid左聯接q在q.id = qa.qid左聯接qz在qz .id = q.qzid,其中qa.pointvalue> 0都選擇fbid userfbid,bn的pointvalue)a.userfbid = c。c.userfbid = b.userfbid

按分數desc按s.userfbid = b.userfbid順序左聯接s

我假設在您的數據庫中s.userFBID.First()永遠不會為null?

如果是正確的話,那么您的問題可能出在FirstOrDefault().Name類型語句中-當FirstOrDefault()計算為null顯然您會得到nullreferenceexception:/

要解決此問題,請嘗試以下操作:

List<reportUser> ru = leaders
        .GroupJoin(db.sweeps,
        a => a.FBID.ToString(),
        s => s.userFBID.First().ToString(),
        (a, matching) => 
        {
            var match = matching.FirstOrDefault();
            return match != null ?
            new reportUser
        {
            FBID = a.FBID,
            CurrentPoints = a.CurrentPoints,
            Name = match.Name,
            Email = match.email
        }
        : new reportUser
        {
            FBID = 0, // a.FBID ?
            CurrentPoints = 0, // a.CurrentPoints ?
            Name = "",
            Email = ""
        }})
        .Select(a => a)
        .ToList();

但是,我發現在不了解數據庫結構或某些示例數據的情況下很難做到這一點


一旦您有工作可用...然后,我強烈建議您嘗試將其分解為更容易理解的內容-我真的不確定這里發生了什么!

這是一個簡單的左外部聯接:

var query = from l leaders
        join s in db.sweeps on l.FBID equals s.userFBID.First() into joined
        from j in joined.FirstOrDefault()
        select new reportUser
    {
        FBID = l.FBID,
        CurrentPoints = l.CurrentPoints,
        Name = j == null ? string.Empty : j.Name,
        Email = j == null ? string.Empty : j.email
    }

如果這不是您要找的東西,請嘗試為您實際想要的發布SQL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM