How to convert SQL query with Unions to LINQ?

前端 未结 1 477
旧时难觅i
旧时难觅i 2021-01-22 10:18

How to convert this one to LINQ?

select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
where d.UserID = 1
/* Friends posts */
Union
select d.UserID, d.Co         


        
1条回答
  •  攒了一身酷
    2021-01-22 10:49

    There is a Union Method in LINQ

    Here is a hint. When things get difficult break them down, then simplify. I will help you break down the problem and leave the simplification to you.

    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);
    

    0 讨论(0)
提交回复
热议问题