如何将带有union的SQL查询转换为LINQ
本文关键字:查询 SQL 转换 LINQ union | 更新日期: 2023-09-27 18:16:48
如何将此转换为LINQ?
select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
where d.UserID = 1
/* Friends posts */
Union
select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
join Friends as fr
on d.UserID = fr.FriendID
where fr.UserID = 1
/* My followings */
Union
select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
join Followers as fl
on d.UserID = fl.FollowerID
where fl.UserID = 1
/* order by UpdateTime desc */
order by 3 desc
我试过了:
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
join fr in db.Friends
on d.UserID equals fr.FriendID
where fr.UserID == userset.ID
join fl in db.Followers
on d.UserID equals fl.UserID
where fl.FollowerID == userset.ID
orderby d.ID descending
select new DiaryPostsSet
{
PostID = d.ID,
EstadoDeAlmaID = e.ID,
EstadoDeAlma = e.Title,
Author = u.Nickname,
Thumbnail = u.Thumbnail,
AuthorComment = d.Content,
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();
它没有显示任何结果。我尝试EF子句,但当我有联盟,我不知道如何执行下一个连接。
谁能帮我一下?LINQ中有一个联合方法
这里有一个提示。当事情变得困难时,把它们分解,然后简化。我将帮你分解这个问题,把简化的工作留给你。
var query1 = (from d in db.DiaryPosts
where d.UserID = 1
select new {
UserID = d.UserID
Content = d.Content
UpdateTime = d.UpdateTime
}).ToList();
var query2 = (from d in db.DiaryPosts
join f in db.Friends
on d.UserId = f.FriendId
where f.UserId = 1
select new {
UserID = d.UserID
Content = d.Content
UpdateTime = d.UpdateTime
}).ToList();
var query3 = (from d in db.DiaryPosts
join f in db.Followers
on d.UserId = f.FollowerID
where f.UserId = 1
select new {
UserID = d.UserID
Content = d.Content
UpdateTime = d.UpdateTime
}).ToList();
var myunionQuery = query1.Union(query2).Union(query3).OrderBy(d => d.UpdateTime);