从LINQ / EF获取前一天n日期数据的有效方法

时间:2013-01-23 21:16:25

标签: c# performance linq entity-framework-4 linq-to-entities

我有一个销售表,其中包含所有订单详细信息。它有列ID,SaleDate,Price。通过Entity Framework v4,在过去30天内获得日常总销售额的有效方法是什么?

public static List<ChartTotal> GetTotalsByDate()
{
    List<ChartTotal> totals = new List<ChartTotal>();
    ChartTotal totalForDay = null;
    DateTime orderDate = DateTime.Now;
    int DAY_COUNT = 30;
    using (LinqModel db = new LinqModel())
    {
        do
        {
        DAY_COUNT--;
        orderDate = orderDate.AddDays(-1);
        totalForDay = new ChartTotal { OrderDate = String.Format("{0:dd MMM}", orderDate), Total = db.Sales.Where(p=>p.SaleDate < orderDate).Sum(o => o.GrandTotal) };
        totals.Add(totalForDay);
        } while (DAY_COUNT > 0);
    }
    return totals;
}

我不希望它如此粗暴。我可以以某种方式获得所有数据,换句话说,我想替换循环,以便我可以最小化往返。我应该选择存储过程吗?

环境:Asp.Net 4.5,EF v4,SQL Sever 2012,VS 2012。

1 个答案:

答案 0 :(得分:3)

这应该为您提供过去30天(包括今天)的每日总数。您可以使用EntityFunctions.TruncateTime来删除DateTime的时间部分。

var q = from x in Sales
        where x.SaleDate > DateTime.Now.AddDays(-30) &&
              x.SaleDate <= DateTime.Now
        group x by EntityFunctions.TruncateTime(x.SaleDate) into g
        select new ChartTotal()
        {
           OrderDate = g.Key,
           Total     = g.Sum(y => y.GrandTotal)
        };