Is Aggregate fatally flawed because each into clause is executed separately?

南楼画角 提交于 2019-11-30 11:58:59

Although it doesn't use the Aggregate keyword, you can do multiple functions in a single query using the following syntax:

Dim query = From book In books _
    Group By key = book.Subject Into Group _
    Select id = key, _
        BookCount = Group.Count, _
        TotalPrice = Group.Sum(Function(_book) _book.Price), _
        LowPrice = Group.Min(Function(_book) _book.Price), _
        HighPrice = Group.Max(Function(_book) _book.Price), _
        AveragePrice = Group.Average(Function(_book) _book.Price)

There does appear to be an issue with the Aggregate clause implementation though. Consider the following query from Northwind:

Aggregate o in Orders
into Sum(o.Freight),
Average(o.Freight),
Max(o.Freight)

This issues 3 database requests. The first two perform separate aggregate clauses. The third pulls the entire table back to the client and performs the Max on the client through Linq to Objects.

Mark Hurd

To answer my broader question: is Aggregate broken for producing separate SQL queries without transactions?

All of LINQ can cause that if you don't carefully adjust your queries to only result in a single SELECT, and that may not be possible, without "giving up", retrieving a larger result in a single query and then using Linq-to-Objects to aggregate or otherwise manipulate the data. This 'query' for example.

So it is, in general, up to the programmer to ensure transactions are added around LINQ queries that may cause multiple queries. We just need to know for sure which LINQ queries may transform into multiple SQL queries.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!