.NET Core实现按日期统计订单总数并展示到DataTable
需求描述
我需要计算每日的订单总数,并将结果按日期逐行展示在DataTable中。统计需基于数据表中的OrderDate字段进行,以获取每日的订单总数。期望得到的统计结果格式如下:
| 日期 | 订单总数 |
|---|---|
| 09.10.2022 | 45 |
| 09.11.2022 | 60 |
| 09.12.2022 | 75 |
Order实体类代码如下:
public class Order : IBaseEntity { [Key] public int OrderId { get; set; } public int UserId { get; set; } public int RestaurantId { get; set; } public int AddressId { get; set; } public int? PromotionId { get; set; } public DateTime OrderDate { get; set; } public DateTime? DeliveryDate { get; set; } public OrderStatues OrderStatus { get; set; } public bool DropDoor { get; set; } public bool RingBell { get; set; } public string OrderNote { get; set; } public OrderTypes OrderType { get; set; } public string PaymentType { get; set; } public decimal SubTotal { get; set; } public decimal DiscountTotal { get; set; } public decimal OrderTotal { get; set; } public decimal DeliveryCost { get; set; } public OrderSources OrderSource { get; set; } public OrderTimes OrderTime { get; set; } public OrderDays OrderDay { get; set; } [NotMapped] public int[] SelectedProducts { get; set; } [NotMapped] public int OrderHour { get; set; } public virtual Restaurant Restaurant { get; set; } public virtual User User { get; set; } public virtual Address Address { get; set; } public virtual Promotion Promotion { get; set; } public virtual ICollection<JoinOrderProduct> JoinOrderProducts { get; set; } = new HashSet<JoinOrderProduct>(); public void Build(ModelBuilder builder) { builder.Entity<Order>(entity => { entity .HasKey(p => new { p.OrderId}); entity .HasOne(p => p.Restaurant) .WithMany(p => p.Orders) .HasForeignKey(p => p.RestaurantId) .OnDelete(DeleteBehavior.Cascade); entity .Property(p => p.SubTotal) .HasPrecision(18, 4) .IsRequired(); entity .Property(p => p.DiscountTotal) .HasPrecision(18, 4) .IsRequired(); entity .Property(p => p.OrderTotal) .HasPrecision(18, 4) .IsRequired(); entity .Property(p => p.DeliveryCost) .HasPrecision(18, 4) .IsRequired(); }); } }
解决方案
1. 编写EF Core查询统计每日订单数
通过EF Core按OrderDate的日期部分分组,统计每组的订单数量:
// 假设你有DbContext实例,命名为_appDbContext var dailyOrders = await _appDbContext.Orders .GroupBy(o => o.OrderDate.Date) // 按日期部分分组,忽略时间维度 .Select(g => new { Date = g.Key.ToString("dd.MM.yyyy"), // 格式化为需求指定的日期格式 OrderCount = g.Count() }) .OrderBy(result => result.Date) // 按日期升序排序 .ToListAsync();
2. 将统计结果转换为DataTable
把查询结果转换成符合要求的DataTable:
DataTable orderTable = new DataTable(); orderTable.Columns.Add("日期", typeof(string)); orderTable.Columns.Add("订单总数", typeof(int)); foreach (var item in dailyOrders) { orderTable.Rows.Add(item.Date, item.OrderCount); }
3. 绑定到UI组件
将生成的DataTable绑定到你的DataTable展示控件(如WinForms的DataGridView、ASP.NET的GridView等),即可得到需求中的展示效果。
注意事项
- 若
OrderDate包含时区信息,建议先统一转换为本地时区或UTC时间后再分组,避免日期统计偏差。 - 如需过滤特定状态的订单(例如仅统计已完成订单),可在查询中添加
Where条件:.Where(o => o.OrderStatus == OrderStatues.Completed)
内容的提问来源于stack exchange,提问作者user19724638
相关产品推荐
相关产品推荐

