我有一个SQl查询工作正常,我需要将其转换为LINQ并遇到一些问题。
我的SQL查询:
select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
where d.UserID = 2
/* friends */
Union
select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
join Friends as fr
on d.UserID = fr.FriendID
where fr.UserID = 2
/* following */
Union
select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
join Followers as fl
on d.UserID = fl.UserID
where fl.FollowerID = 2
/* ordenando por UpdateTime desc */
order by 3 desc
我根据my own previous question尝试的内容:
var friends = (from u in db.User
join f in db.Friends
on u.ID equals f.FriendID
where f.UserID == userset.ID
orderby u.Nickname
select new FriendsSet { ID = u.ID, Nickname = u.Nickname, Thumbnail = u.Thumbnail }).ToList();
var followers = (from u in db.User
join f in db.Followers
on u.ID equals f.FollowerID
where f.UserID == userset.ID
orderby u.Nickname
select new FriendsSet { ID = u.ID, Nickname = u.Nickname }).ToList();
var diaryPosts = (from d in db.DiaryPosts
join e in db.EstadosDeAlma
on d.EstadosDeAlmaID equals e.ID
join u in db.User
on d.UserID equals u.ID
where d.UserID == userset.ID
select new DiaryPostsSet {
PostID = d.ID,
EstadoDeAlmaID = e.ID,
EstadoDeAlma = e.Title,
Author = u.Nickname,
Thumbnail = u.Thumbnail,
UserID = u.ID,
IsDuplicated = d.IsDuplicated,
FriendID = d.FriendID,
FriendName = u.Nickname,
Time = d.UpdateTime,
MessagesCount = d.FriendMessages.Count(m => m.DiaryPostsID == d.ID)
}).Take(6).ToList();
var diaryPostsUnion = diaryPosts.Union(friends).Union(followers).OrderBy(d => d.UpdateTime);
我得到的错误:
'System.Collections.Generic.List<MvcWebRole1.Models.DiaryPostsSet>' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.ParallelEnumerable.Union<TSource>(System.Linq.ParallelQuery<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments
Instance argument: cannot convert from 'System.Collections.Generic.List<MvcWebRole1.Models.DiaryPostsSet>' to 'System.Linq.ParallelQuery<MvcWebRole1.Models.FriendsSet>'
答案 0 :(得分:1)
您尝试将一种类型的序列与另一种类型的序列联合起来。这没有道理 - 基本上,工会必须是相同的类型。
你在这里尝试做什么并不是很清楚,但我怀疑你不想要一个工会。
哦,如果你想在数据库中发生所有这些,请摆脱ToList
电话。
编辑:好的,很难确切看到你的LINQ查询对应于你的SQL查询,但基本上你的“选择”条款应该是这样的:
from d in db.DiaryPosts
// stuff here
select new { UserID = d.ID, d.UpdateTime, d.Content }
在每个查询中使用完全相同的匿名类型 - 相同的属性名称和类型,顺序相同 - 您应该能够使用Union
方法。