2017-03-23 97 views
1

有没有一种方法来实现我使用LINQ获得的所有可查询对象?实现所有查询对象

比方说,我想作者的列表,基于某些标准的图书(这是一个示例查询,我希望一些实际的类是没有必要)的列表:

var authorData = from a in ctx.Authors 
       where a.Age > 30 
       select new // anon class 
       { 
        Name = a.Name, 
        City = a.Address.City, 
        Books = from b in ctx.Books 
          where b.Price > 10 
          && b.AuthorId == a.Id 
          select new // anon class 
          { 
           Name = b.Name, 
           Price = b.Price, 
          } 
       }; 

现在我想要遍历作者authorData并做一些工作,可以说打印书数。书籍列表将是IQueryable类型,并且为每个作者获取这些对象将产生一个新的查询到我想要避免的DB。

foreach(var author in authorData.ToList()) 
{ 
    Console.WriteLine(author.Books.Count()); 
} 

如何避免每个作者的新SQL查询?有没有办法让书籍匿名类对象与作者匿名类同时实现?

编辑: 的最终目标是让尽可能少的DB读数可能的,但有所有的AuthorBook对象。在每个foreach循环迭代中实现书籍看起来很可怕。

我甚至会接受一个答案,将得到像词典之类的,让作者/预订连接方便单独藏书的对象,但并不需要很多数据库读取

回答

-2
var authorData = (from a in ctx.Authors 
      where a.Age > 30 
      select new // anon class 
      { 
       Name = a.Name, 
       City = a.Address.City, 
       Books = from b in ctx.Books 
         where b.Price > 10 
         && b.AuthorId == a.Id 
         select new // anon class 
         { 
          Name = b.Name, 
          Price = b.Price, 
         } 
      }).ToList(); 
+0

这是我尝试的第一件事,但它仍然将本书作为IQueryable离开课堂。 –

0

你可以使用ToList ()方法用于书籍查询和外部查询。

var authorData = (from a in ctx.Authors 
     where a.Age > 30 
     select new // anon class 
     { 
      Name = a.Name, 
      City = a.Address.City, 
      Books = (from b in ctx.Books 
        where b.Price > 10 
        && b.AuthorId == a.Id 
        select new // anon class 
        { 
         Name = b.Name, 
         Price = b.Price, 
        }).ToList() 
     }).ToList(); 
foreach(var author in authorData) 
    { 
    Console.WriteLine(author.Books.Count()); 
    } 
+0

这给我一个例外... –

+0

@TadijaBagarić什么是例外? –

+0

我认为这个异常是由b.Price为空的。你可以通过改变这个来解决这个问题b.Price? 0.匿名类型需要相同的顺序和类型。所以价格可能是整数,如果价格为空,这会导致豁免。 –

相关问题