我有一种方法,它使用实体框架为服务点应用程序查询 SQL Server CE 数据库并打印结果。我使用的代码有效,但是当数据库大小增加时,该方法需要更长的时间来执行。我认为这是因为数据库被多次查询以达到预期的结果。我真正想做的是查询数据库一次并将结果存储在内存中,然后针对存储在内存中的数据运行所有其他查询。
该方法主要需要查询数据库以查找今天的交易(ZTotaled == null),然后打印交易日每30分钟的交易数量和总销售额。
我正在使用的代码看起来像这样......
var ztotal = from z in context.Transactions
where z.ZTotaled == null
select new { z.NumerPeople, z.PricePaid, z.ZTotaled, z.DateTime };
var ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 18 && z.DateTime.Minute < 30
select new { z.NumerPeople, z.PricePaid };
totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);
sb2.Append(string.Format("{0}{1,10}{2,16}", "18.00 - 18.30", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);
ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 18 && z.DateTime.Minute >= 30
select new { z.NumerPeople, z.PricePaid };
totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);
sb2.Append(string.Format("{0}{1,10}{2,16}", "18.30 - 19.00", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);
ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 19 && z.DateTime.Minute < 30
select new { z.NumerPeople, z.PricePaid };
totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);
sb2.Append(string.Format("{0}{1,10}{2,16}", "19.00 - 19.30", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);
ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 19 && z.DateTime.Minute >= 30
select new { z.NumerPeople, z.PricePaid };
totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);
sb2.Append(string.Format("{0}{1,10}{2,16}", "19.30 - 20.00", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);
ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 20 && z.DateTime.Minute < 30
select new { z.NumerPeople, z.PricePaid };
totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);
sb2.Append(string.Format("{0}{1,10}{2,16}", "20.00 - 20.30", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);
有人可以指点我使这段代码更有效率的方向吗?
非常感谢
詹姆士