gpt4 book ai didi

c# - 如何将带联合的 SQL 查询转换为 LINQ?

转载 作者:行者123 更新时间:2023-11-30 22:33:15 26 4
gpt4 key购买 nike

如何将这个转换为 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 子句,但是当我有 Union 时,我不知道如何执行下一个 Join。

谁能帮帮我?

最佳答案

有一个Union Method在 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);

关于c# - 如何将带联合的 SQL 查询转换为 LINQ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8394111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com