使用linq查询时出现运行时错误

时间:2013-10-31 14:52:15

标签: c# asp.net linq linq-to-sql linq-to-entities

我能够为Web Api编写此代码。在这段代码中,我编写了两个查询,并以一种方式结合两者,即评论和跟随者数据应该基于ctime合并(不合并)时间并开始跟随。如果用户有新评论,则评论应该首先出现,如果跟随者是第一个,那么跟随者数据应该是第一个。

 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 个答案:

答案 0 :(得分: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);

工会现在应该成功,以及订购和最终预测。