如何:聚合数据(实体框架)

聚合运算从值的集合中计算出单个值。 例如,从一个月累计的每日温度值计算出日平均温度值就是一个聚合运算。 此主题说明如何按联系人 ID 对订单进行分组,并获取每个联系人 ID 的平均应付总金额。

使用 LINQ to Entities 和 Entity SQL 演示同一示例:

  • LINQ to Entities

  • Entity SQL 以及 ObjectQuery<T>

本主题中的示例基于 Adventure Works 销售模型。若要运行本主题中的代码,则必须已经将 Adventure Works 销售模型添加到了您的项目中,并且已经将项目配置为使用实体框架。有关更多信息,请参见如何:使用实体数据模型向导(实体框架)如何:手动配置实体框架项目如何:手动定义实体数据模型(实体框架)

示例

以下是 LINQ to Entities 示例。

Using context As New AdventureWorksEntities
    Dim orders As ObjectSet(Of SalesOrderHeader) = context.SalesOrderHeaders

    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 context = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;

    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 context As New AdventureWorksEntities()
    Dim esqlQuery As String = "SELECT contactID, AVG(order.TotalDue) FROM AdventureWorksEntities.SalesOrderHeaders " & _
        " AS order GROUP BY order.Contact.ContactID as contactID"

    For Each rec As DbDataRecord In New ObjectQuery(Of DbDataRecord)(esqlQuery, context)
        Console.WriteLine("ContactID = {0} Average TotalDue = {1} ", rec(0), rec(1))
    Next
End Using
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    string esqlQuery = @"SELECT contactID, AVG(order.TotalDue) 
                            FROM AdventureWorksEntities.SalesOrderHeaders 
                            AS order GROUP BY order.Contact.ContactID as contactID";

    foreach (DbDataRecord rec in
        new ObjectQuery<DbDataRecord>(esqlQuery, context))
    {
        Console.WriteLine("ContactID = {0}  Average TotalDue = {1} ",
            rec[0], rec[1]);
    }
}

另请参见

任务

如何:对数据分组(实体框架)