按年和月加入linq和group

时间:2016-04-02 22:31:15

标签: c# linq join group-by

我有以下linq查询,我的目标是按年份和月份进行分组并进行一些计算:我已经设置了ViewModel。我甚至不确定我的查询是否会按预期工作,因为它无法编译。我收到此错误

System.NotSupportedException was unhandled by user code
  HResult=-2146233067
  Message=LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable`1[System.Int32] Range(Int32, Int32)' method, and this method cannot be translated into a store expression.
  Source=EntityFramework

控制器代码

 public ActionResult Summary(int? yr, int? mn, int? BkId)
             {
                 var squery = SummaryYrMn(yr, mn, BkId);
                 return View(squery);
             }    

    public IEnumerable SummaryYrMn()
                 {
         var squery =
        (from bk in db.Books
        from year in Enumerable.Range(2010, DateTime.Today.Year)
        from month in Enumerable.Range(1, 12)
        let key = new { Year = year, Month = month }

        //sold books
        join tr in db.Transacts.Where(a => a.TransactTypeId==1 && a.Book.BookTypeId==1 ) on key
        equals new{tr.TransactDate.Year, tr.TransactDate.Month} into s

        //gifted books
        join tr2 in db.Transacts.Where(a => a.TransactTypeId == 2 && a.Book.BookTypeId == 1) on key
        equals new{tr2.TransactDate.Year, tr2.TransactDate.Month} into t

        //gifted  tracts books  book type = tract
      join tr3 in db.Transacts.Where(a => a.TransactTypeId == 2 && a.Book.BookTypeId == 2) on key
      equals new { tr3.TransactDate.Year, tr3.TransactDate.Month } into u

        select new SummaryViewModel
         {

      Year = year,
      Month = month,
      Gifted = (int?)t.Sum(c => c.TransactQty) ?? 0,
      GSales = (int?)s.Sum(c => c.TransactQty) ?? 0,
      GiftedTracts = (int?)u.Sum(c => c.TransactQty) ?? 0,
      TotalGift = ((int?)t.Sum(c => c.Book.BookPrice))*((int?)s.Sum(c => c.TransactQty)??0),
      TotalSale =   ((int?)s.Sum(c => c.TransactPrice))*((int?)s.Sum(c => c.TransactQty)??0)

       });

        return squery.AsEnumerable();
   }

1 个答案:

答案 0 :(得分:0)

尝试启动方法SummaryYrMn,如此...

NSAssert([NSThread isMainThread)];

Enumarable.Range()正由Linq-to-Entities转换为SQL,并且不存在于sql上下文中。