2011-12-06 50 views
2

如何將其轉換爲LINQ?如何將SQL查詢與聯合體轉換爲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。

任何人都可以幫助我嗎?

+0

您能否提供您嘗試過的樣品? –

+0

是它的編輯...你可以看到我完全失去了,我是新來的LINQ –

回答

3

有一個在LINQ

一個Union Method這裏是一個暗示。當事情變得困難時,將其分解,然後簡化。我會幫助你解決問題,並將簡化交給你。

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

你有什麼嘗試?你能舉一個例子來描述你所遇到的問題嗎? –

+0

好的,它的編輯。 –