我正在尝试创建一个销售报告,用户可以在其中选择日期范围并获取每天的销售额和日期时间。
我已经制作了一个方法,它需要两个日期时间 - StartDate和EndDate,并在这些日子之间的所有日子循环对象,这样即使当天没有销售,我也可以返回Date和TotalSales = 0
然后我将此加入我的GetOrders查询。如果我有一个日期的intervall,例如2017-04-01 - 2017-04-30,这可以正常工作,但如果我发送了同一天的startdate和enddate,我的结果会错误。我做错了什么想法?
课程:
public class Order
{
public int Id { get; set; }
public DateTime OrderDate { get; set; }
public virtual ICollection<OrderItem> OrderItems { get; set; }
}
public class OrderItem
{
public int Id { get; set; }
public decimal UnitPrice { get; set; }
public int Quantity { get; set; }
public int Discount { get; set; }
public virtual Order Order { get; set; }
}
public class DailySalesDto
{
public DateTime Date { get; set; }
public decimal TotalSales { get; set; }
}
帮助方法:
public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
控制器:
public IEnumerable<DailySalesDto> GetOrders(DateTime startDate, DateTime
endDate)
{
var DateRange = new List<DailySalesDto>();
foreach (DateTime day in EachDay(startDate, endDate))
{
DailySalesDto newEmpty = new DailySalesDto()
{
Date = day,
TotalSales = 0
};
DateRange.Add(newEmpty);
}
var salesForPeriod = db.Orders.Where(b => b.OrderDate.Day > startDate.Day && b.OrderDate.Day <= endDate.Day);
var salesByDay = from s in salesForPeriod
group s by s.OrderDate.Day into g
select new { Date = g.Key, totalSales = g.Sum(p => p.OrderItems.Select(x => x.Quantity * x.UnitPrice).Sum()) };
var query = from d in DateRange
join s in salesByDay on d.Date.Day equals s.Date into j
from s in j.DefaultIfEmpty()
select new DailySalesDto { Date = d.Date, TotalSales = (s != null) ? s.totalSales : 0m };
return query.OrderBy(x => x.Date.Day);
}
结果2017-04-25 - 2017-04-25(现有2个订单)
/ API / SalesVM /的startDate = 2017年4月26日&安培;结束日期= 2017年4月26日
[
{
"Date": "2017-04-26T00:00:00",
"Day": 0,
"TotalSales": 0
}
]
/ API / SalesVM /的startDate = 2017年4月25日&安培;结束日期= 2017年4月26日
[
{
"Date": "2017-04-25T00:00:00",
"Day": 0,
"TotalSales": 0
},
{
"Date": "2017-04-26T00:00:00",
"Day": 0,
"TotalSales": 247
}
]
答案 0 :(得分:3)
使用&gt; =获取salesForPeriod开始日期
var salesForPeriod = db.Orders.Where(b => b.OrderDate.Day >= startDate.Day && b.OrderDate.Day <= endDate.Day);