在图表

时间:2017-03-08 00:55:29

标签: asp.net asp.net-mvc linq charts

我不知道如何在开头显示asp.net MVC中表中月份的总和。 表格中的数据如下所示:

  

DateCreated | TotalPrice
    2017-02-06 | 400
    2017-02-06 | 300
    2017-03-06 | 100
    2017-03-06 | 50

我希望得到TotalPrice的总和,如下所示:

  

DateCreated | TotalPrice
    2017-02 | 700
    2017-03 | 150

我的模特课顺序:

public int orderId { get; set; }
    public string UserId { get; set; }
    public virtual ApplicationUser User { get; set; }
    [StringLength(100)]
    public string firstName { get; set; }
    [StringLength(150)]
    public string lastName { get; set; }
    [StringLength(150)]
    public string address { get; set; }
    [StringLength(20)]
    public string phoneNumber { get; set; }
    public string email { get; set; }

    public string comment { get; set; }
    public DateTime dateCreated { get; set; }
    public OrderState orderState { get; set; }
    public decimal totalPrice { get; set; }

    public List<OrderIteam> OrderIteams { get; set; }

我尝试写这样的东西来显示表中月份的总和:

public ActionResult ListOrder()
{
    var result =
        from s in db.Orders
        group s by new { date = new DateTime(s.dateCreated.Year, s.dateCreated.Month, 1) } into g
        select new
        {
            dateCreated = g.Key.date,
            sumTotalPrice = g.Sum(x => x.totalPrice)
        };
    return View(result);
}

My view looks like this

我收到错误消息:

  

传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery 1[<>f__AnonymousType5 2 [System.DateTime,System.Decimal]]',但此字典需要类型的模型项'System.Collections.Generic.IEnumerable`1 [Sklep_Internetowy.Models.Order]'。

最后,我想表明给定月份的订单总和如下图所示: Chart

1 个答案:

答案 0 :(得分:0)

目前,下面的LINQ查询返回DbQuery实例,其中包含匿名类型而不是IEnumerable集合:

var result = from s in db.Orders
             group s by new { date = new DateTime(s.dateCreated.Year, s.dateCreated.Month, 1) } into g
             select new
             {
                 dateCreated = g.Key.date,
                 sumTotalPrice = g.Sum(x => x.totalPrice)
             }; // returns System.Data.Entity.Infrastructure.DbQuery<AnonymousTypeN>

抛出InvalidOperationException背后的原因仅仅是因为已经将不同类型的数据传递到需要IEnumerable<Sklep_Internetowy.Models.Order>的视图中。

尝试使用匿名类型1更改返回类型为Order

var result = from s in db.Orders
             group s by new { date = new DateTime(s.dateCreated.Year, s.dateCreated.Month, 1) } into g
             select new Order // return Sklep_Internetowy.Models.Order here
             {
                 dateCreated = g.Key.date,
                 sumTotalPrice = g.Sum(x => x.totalPrice)
             };

此时,上面的LINQ查询的返回类型变为IQueryable<Sklep_Internetowy.Models.Order>,它实现IEnumerable,因此它不需要转换(但您可能仍需要use collection aggregate methods to execute it,例如{ {1}})。

相关问题:

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery', but this dictionary requires a model item of type B

The model item passed into the dictionary is 'System.Data.Entity.Infrastructure.DbQuery`, but requires 'System.Collections.Generic.IEnumerable