2014-10-18 37 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