Register表是保存来访客人登记信息的。还有Gifts表是保存客人所赠的礼品的。两者存在主外键关系。我需要根据区域,或者时间检索出信息,然后找到礼物表中的多条记录。统计这些记录的总金额。请问怎么做呢??
检索以实现。
public ActionResult Statistics(string Area, DateTime? startTime, DateTime? endTime, int pageindex = 1)
{
//开始日期的上午12:00.结束日期的上午12:00.
// endTime = endTime.Value.AddDays(1);是包括结束日期。
var staInfo = PredicateBuilder.True<Register>();
if (Area != null && Area.Trim() != "")
{
staInfo = staInfo.And(p => p.Area.Contains(Area));
}
if (startTime != null)
{
ViewBag.startTime = startTime;
staInfo = staInfo.And(p => p.AddTime >= startTime);
}
if (endTime != null)
{
ViewBag.endAddTime = endTime;
endTime = endTime.Value.AddDays(1);
staInfo = staInfo.And(p => p.AddTime <= endTime);
}
PagedList<Register> list = db.Set<Register>().Where(staInfo).OrderByDescending(p => p.AddTime).ToPagedList(pageindex, 10);
ViewBag.count = db.Set<Register>().Where(s => true).ToList().Count();
ViewBag.model = list;
for(int i=0;i<ViewBag.count;i++){
}
return View(list);
}
这个一个查询就搞定了,最好贴出你的表结构、数据和想要的结果,你贴这些代码没用。
已解决
//listAll为了知道所有的记录。如果分页超过1页总金额会只计算这1页10条记录的。
var listAll = db.Set<Register>().Where(staInfo).OrderByDescending(p => p.AddTime).ToList();
//list为分页。
PagedList<Register> list = db.Set<Register>().Where(staInfo).OrderByDescending(p => p.AddTime).ToPagedList(pageindex, 10);
ViewBag.count = db.Set<Register>().Where(s => true).ToList().Count();
ViewBag.model = list;
//totalMoney每条记录中的总金额。
decimal totalMoney = 0;
//遍历list集合找到Gifts表中
foreach (var item in listAll)
{
var lists = db.Set<Gifts>().Where(s => s.IsDelete == false && s.RegisterID == item.ID).ToList().FirstOrDefault();
if (lists != null)
{
totalMoney += Convert.ToDecimal((lists.WineMoney == null ? 0 : lists.WineMoney) + (lists.DangerMoney == null ? 0 : lists.DangerMoney) + (lists.HealthMoney == null ? 0 : lists.HealthMoney) + (lists.PromotionMoney == null ? 0 : lists.PromotionMoney));
}
}
ViewBag.TotalMoney = totalMoney;
return View(list);