2013-10-31 69 views
0

我能夠爲Web Api編寫此代碼。在這段代碼中,我編寫了兩個查詢,並將兩者結合起來,評論和跟隨者數據應該根據ctime合併(不合並)時間,並開始執行以下操作。如果用戶有新的評論,評論應該是第一位的,如果跟隨者是第一位,那麼跟隨者的數據應該是第一位的。使用linq查詢時的運行時錯誤

public IQueryable<Object> GetCommentsandFollowActivityCommnets() 
    { 

     var combo1 = from c in db.comments 
        join p in db.picturedetails on c.targetpictureid equals p.idpictures 
        join u in db.users on c.iduser equals u.iduser 
        select new TCommentDTO 
        { 

         idcomments=c.idcomments, 
         comment1 = c.comment1, 
         targetpictureid = c.targetpictureid, 
         ctime = c.ctime, 
         iduofpic=p.iduser, 
         iduofcommentor=c.iduser, 
         profilepicofcommentor=u.profilepic, 
         usernameofcommentor=u.username, 
         picFilename=p.picFilename, 
         picTitle=p.picTitle 

        }; 

     var combo2= from f in db.followers 
        join u in db.users on f.iduser equals u.iduser 
        select new TfollowerDTO 
        {  
         idfollowers=f.idfollowers, 
         iduser=f.iduser, 
         targetiduser=f.targetiduser, 
         startedfollowing=f.startedfollowing, 
         unoffollower=u.username, 
         ppoffollower=u.profilepic, 
         status=u.status 


        }; 
      var result1 = from c in combo1 
      select new UserTimeLineDTO 
      { SortKey = c.ctime, Member =c}; 

      var result2 = from c in combo2 
      select new UserTimeLineDTO{ SortKey = c.startedfollowing, Member = c }; 

      var result = result1.Concat(result2).OrderBy(x =>x.SortKey).Select(x => x.Member); 

      return result; 

    } 

該代碼沒有給出任何編譯時錯誤。它運行良好的編譯器,但在運行時我收到一個異常:

DbUnionAllExpression requires arguments with compatible collection ResultTypes. 

如何刪除此異常?

回答

1

作爲一種變通方法,我會嘗試在內存中來評估最後一個表達式:

 var result1 = (from c in combo1 
     select new UserTimeLineDTO 
     { SortKey = c.ctime, Member =c}).ToList(); 

     var result2 = (from c in combo2 
     select new UserTimeLineDTO{ SortKey = c.startedfollowing, Member = c }).ToList(); 

     var result = result1.Concat(result2).OrderBy(x =>x.SortKey).Select(x => x.Member); 

工會現在應該成功,以及訂購和最終投射。

+0

它的工作,你能解釋爲什麼/如何? – Obvious

+1

.ToList強制評估並實現內存中的對象。這樣Concat在內存中而不是在數據庫端進行評估。 –