C# 使用linq查询时出现运行时错误
我能够为Web Api编写此代码。在这段代码中,我编写了两个查询,并以一种基于ctime和startedfollowing的时间合并(而不是合并)注释和跟随者数据的方式组合了这两个查询。如果用户有新的注释,则注释应排在第一位,如果跟随者是第一位的,则跟随者数据应排在第一位C# 使用linq查询时出现运行时错误,c#,asp.net,linq,linq-to-sql,linq-to-entities,C#,Asp.net,Linq,Linq To Sql,Linq To Entities,我能够为Web Api编写此代码。在这段代码中,我编写了两个查询,并以一种基于ctime和startedfollowing的时间合并(而不是合并)注释和跟随者数据的方式组合了这两个查询。如果用户有新的注释,则注释应排在第一位,如果跟随者是第一位的,则跟随者数据应排在第一位 public IQueryable<Object> GetCommentsandFollowActivityCommnets() { var combo1 = from c in db.
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;
}
如何删除此异常?作为一种解决方法,我将尝试计算内存中的最后一个表达式:
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在内存中而不是在数据库端进行计算。
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);