【问题标题】:Runtime error while using a linq query使用 linq 查询时出现运行时错误
【发布时间】:2013-11-11 15:34:57
【问题描述】:

我可以为 Web Api 编写此代码。在这段代码中,我编写了两个查询,并以 cmet 和跟随者数据应该根据 ctime 和 startfollowing 的时间合并(而不是合并)的方式进行组合。如果用户有新评论,则评论应在前,如果关注者在前,则关注者数据应在前。

 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.

如何去除这个异常?

【问题讨论】:

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


    【解决方案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);
    

    联合现在应该成功了,排序和最终投影也是如此。

    【讨论】:

    • .ToList 强制评估并在内存中实现对象。这样,Concat 在内存中而不是在数据库端进行评估。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多