C# 从LINQ/EF获取前n天逐日期数据的有效方法
我有一个包含所有订单详细信息的销售表。它有ID、SaleDate、Price列。通过Entity Framework v4,获取前30天每日总销售额的有效方法是什么C# 从LINQ/EF获取前n天逐日期数据的有效方法,c#,performance,linq,entity-framework-4,linq-to-entities,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; DateT
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;
}
public静态列表GetTotalsByDate()
{
列表总计=新列表();
ChartTotalForDay=null;
DateTime orderDate=DateTime.Now;
int DAY_计数=30;
使用(LinqModel db=new LinqModel())
{
做
{
天啊;
orderDate=orderDate.AddDays(-1);
totalForDay=new ChartTotal{OrderDate=String.Format(“{0:dd MMM}”,OrderDate),Total=db.Sales.Where(p=>p.SaleDateo.GrandTotal)};
总计。添加(totalForDay);
}而(天数>0);
}
返回总数;
}
我不希望它做得这么粗糙。我能一次获得所有数据吗,换句话说,我想替换循环,这样我就可以最小化往返。我应该改为使用存储过程吗
环境:Asp.Net 4.5,EF v4,SQL Server 2012,VS 2012。这将为您提供过去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)
};
var q=来自销售中的x
其中x.SaleDate>DateTime.Now.AddDays(-30)&&
x、 销售日期(总计)
};
SaleDate包括时间还是仅包括日期?包括日期和时间。谢谢,伙计。不得不使用这个EntityFunctions.AddDays(DateTime.Now,-30)
类EntityFunctions
已被DbFunctions