不支持聚合扩展方法(Linq to Sql) [英] Aggregate Extension Method Not Supported (Linq to Sql)

查看:83
本文介绍了不支持聚合扩展方法(Linq to Sql)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在linq to Sql中使用Aggregate Method,但看起来好像不支持它.

I was trying to use Aggregate Method in linq to Sql but looks like it is not supported.

LibrarySystemDataContext ctx = new LibrarySystemDataContext();

var query = ctx.Books
  .Select(x => new
      {
        BookID = x.BookID,
          BookName = x.Title,
          Authors = x.AuthorBooks.Select(a => a.Author)
          .Aggregate(new StringBuilder(), (sb, r) => sb.Append(r.FirstName + " " + r.LastName +"& "), sb => sb.ToString())
          });

要使用Aggregate,我立即将图书转换为IEnumerable,如下所示:

to use Aggregate, i immediately converted books to IEnumerable as follows:

var query = ctx.Books.AsEnumerable()
  .Select(x => new
      {
        BookID = x.BookID,
          BookName = x.Title,
          Authors = x.AuthorBooks.Select(a => a.Author)
          .Aggregate(new StringBuilder(), (sb, r) => sb.Append(r.FirstName + " " + r.LastName +"& "), sb => sb.ToString())
          });

而且,这是可行的.我想知道如果我编写这样的查询会带来什么弊端或设计缺陷.

And, this is working. I want to know what will be the drawbacks or design flaws if i write queries like this.

推荐答案

ctx.Books.AsEnumerable()一起,您将从数据库中选择整个books表,并开始在内存中对其进行处理.这不是一个好的设计.您应该做的是,选择所需的数据,然后在本地进行处理.

with ctx.Books.AsEnumerable() you will select the whole books table from database and start processing it in memory. This isn't good design. What you should do is, select the data you need and then process it locally.

例如

var temp = ctx.Books
  // probably some where clause
  .Select(x => new
      {
        BookID = x.BookID,
          BookName = x.Title,
          Authors = x.AuthorBooks.Select(a => a.Author)
          })
  .ToArray();

var books = temp.Select(x => new { 
    x.BookID, 
    x.BookName, 
    Authors = x.Authors.Aggregate(new StringBuilder(), (sb, r) => sb.Append(r.FirstName + " " + r.LastName +"& "), sb => sb.ToString()) 
});

这篇关于不支持聚合扩展方法(Linq to Sql)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆