如何:聚合数据(实体框架)
聚合运算从值的集合中计算出单个值。例如,从一个月累计的每日温度值计算出日平均温度值就是一个聚合运算。此主题说明如何按联系人 ID 对订单进行分组,并获取每个联系人 ID 的平均应付总金额。
将使用以下每种 实体框架 查询技术演示同一示例:
LINQ to Entities
Entity SQL with ObjectQuery<T>
本主题中的示例基于 Adventure Works 销售模型。若要运行本示例中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用实体框架。为此,请完成如何:手动配置实体框架项目和如何:手动定义实体数据模型(实体框架) 中的过程。也可以使用实体数据模型向导定义 AdventureWorks 销售模型。有关更多信息,请参见如何:使用实体数据模型向导(实体框架)。
示例
以下是 LINQ to Entities 示例。
Using AWEntities As New AdventureWorksEntities
Dim orders As ObjectQuery(Of SalesOrderHeader) = AWEntities.SalesOrderHeader
Dim query = _
From ord In orders _
Let contID = ord.Contact.ContactID _
Group ord By contID Into g = Group _
Select New With _
{ _
.Category = contID, _
.averageTotalDue = _
g.Average(Function(ord) ord.TotalDue) _
}
For Each ord In query
Console.WriteLine("ContactID = {0} " & vbTab & _
" Average TotalDue = {1}", _
ord.Category, ord.averageTotalDue)
Next
End Using
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
ObjectQuery<SalesOrderHeader> orders = AWEntities.SalesOrderHeader;
var query =
from order in orders
group order by order.Contact.ContactID into g
select new
{
Category = g.Key,
averageTotalDue = g.Average(order => order.TotalDue)
};
foreach (var order in query)
{
Console.WriteLine("ContactID = {0} \t Average TotalDue = {1}",
order.Category, order.averageTotalDue);
}
}
以下是 Entity SQL 示例。
Using advWorksContext As AdventureWorksEntities = New AdventureWorksEntities
Dim esqlQuery As String = "SELECT contactID, AVG(order.TotalDue) " & _
" FROM(AdventureWorksEntities.SalesOrderHeader)" & _
" AS order GROUP BY order.Contact.ContactID as contactID"
Try
Dim rec As DbDataRecord
Dim query As New ObjectQuery(Of DbDataRecord)(esqlQuery, advWorksContext)
For Each rec In query
Console.WriteLine("ContactID = {0} Average TotalDue = {1} ", _
rec.Item(0), rec.Item(1))
Next
Catch ex As EntityException
Console.WriteLine(ex.ToString())
Catch ex As InvalidOperationException
Console.WriteLine(ex.ToString())
End Try
End Using
using (AdventureWorksEntities advWorksContext =
new AdventureWorksEntities())
{
string esqlQuery = @"SELECT contactID, AVG(order.TotalDue)
FROM AdventureWorksEntities.SalesOrderHeader
AS order GROUP BY order.Contact.ContactID as contactID";
try
{
foreach (DbDataRecord rec in
new ObjectQuery<DbDataRecord>(esqlQuery, advWorksContext))
{
Console.WriteLine("ContactID = {0} Average TotalDue = {1} ",
rec[0], rec[1]);
}
}
catch (EntityException ex)
{
Console.WriteLine(ex.ToString());
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.ToString());
}
}