2014-10-18 61 views
0

我有這樣的代碼:簡化了兩個查詢到一個與同類型的LINQ

var commentData = from o in quack.BlogComments 
        join u in quack.AdminUsers 
        on o.UserId equals u.AdminUserId 
        where blogid == o.BlogId 
        select new 
        { 
         o.Comment, 
         o.CommentDate, 
         u.FirstName, 
         u.LastName 
        }; 

var commentData2 = from o in quack.BlogComments 
        join u in quack.RegularUsers 
        on o.UserId equals u.RegularUserId 
        where blogid == o.BlogId 
        select new 
        { 
         o.Comment, 
         o.CommentDate, 
         u.FirstName, 
         u.LastName 
        }; 

var l = commentData.ToList(); 
l.AddRange(commentData2); 

正如你可以在上面看到我在做2不同的查詢到數據庫中,然後加在一起,以產生一個gridview中使用單個列表

我想要的只是使用1查詢到數據庫,並將導致這些表中的兩個相結合。

我該怎麼辦?有多個連接可能嗎?

回答

1

你應該使用Concat

var commentData = (from o in quack.BlogComments 
        join u in quack.AdminUsers 
        on o.UserId equals u.AdminUserId 
        where blogid == o.BlogId 
        select new 
        { 
         o.Comment, 
         o.CommentDate, 
         u.FirstName, 
         u.LastName 
        }).Concat(from o in quack.BlogComments 
          join u in quack.RegularUsers 
          on o.UserId equals u.RegularUserId 
          where blogid == o.BlogId 
          select new 
          { 
           o.Comment, 
           o.CommentDate, 
           u.FirstName, 
           u.LastName 
          }); 

var l = commentData.ToList(); 
+0

它更有意義的寫'變種L = commentData.Concat(commentData2).ToList()'沒有這種嵌套查詢?我們也很高興地注意到,Lint to Sql能夠通過'UNION'形成一個sql查詢,從而實現數據庫的單次往返。 – 2014-10-18 03:09:37

+0

是的,會給出完全相同的結果。 – MarcinJuraszek 2014-10-18 03:10:14

+0

@MarcinJuraszek這仍然會導致2個不同的queiry到數據庫? – 2014-10-18 03:19:57