我试图在linq中使用聚合方法到Sql,但看起来它不受支持。
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,如下所示:
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())
});
而且,这是有效的。我想知道如果我写这样的查询会有什么缺点或设计缺陷。
答案 0 :(得分:1)
使用ctx.Books.AsEnumerable()
,您将从数据库中选择整本书籍表并开始在内存中处理它。这不是好设计。您应该做的是,选择您需要的数据,然后在本地处理它。
例如
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())
});