Aggregate Extension Method Not Supported (Linq to

2019-09-06 19:17发布

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())
          });

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.

标签: c# linq lambda
1条回答
疯言疯语
2楼-- · 2019-09-06 20:00

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.

for example

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()) 
});
查看更多
登录 后发表回答