Linq Entity Framework分组并加入名称,年份和月份

时间:2016-04-06 00:25:03

标签: c# mysql asp.net-mvc linq

我正在使用MYSQL和Entity Framework开发ASP.NET MVC应用程序。我有客户对某些付款类别进行付款。我想开发一个分类帐,其中我有客户名称和所有类别的付款,每个客户为任何特定的付款类别支付总额。而且我将按名称,年份和月份进行分组。并且能够按年,月或customerid进行过滤。我有25个付款类别。

我所做的解决方案是古老的 - 它使用25个连接来获取类别,将付款总和并将它们分配给视图模型。这在我的开发机器上运行正常,但它在我的服务器上失败并出现错误

MySql.Data.MySqlClient.MySqlException: Too high level of nesting for select

任何人都可以给我一个更好的方法来实现这个目标

我的代码如下所示

public ActionResult LedgerReport(int? year, int? month, int? CuId)
{
var query = LedgerYrMn(year, month, CuId);
return View(query);
}

public IEnumerable LedgerYrMn(int? year, int? month, int? CuId)
{
DateTime lastmonth = DateTime.Now;
DateTime thismonth = DateTime.Now;
DateTime thismonthstart = DateTime.Now;

if (year.HasValue && month.HasValue)
  {
lastmonth = (new DateTime(year.Value, month.Value, DateTime.DaysInMonth(year.Value, month.Value)).AddMonths(-1));
thismonth = (new DateTime(year.Value, month.Value, DateTime.DaysInMonth(year.Value, month.Value)));
thismonthstart = (new DateTime(year.Value, month.Value, 1));
                    }
var query =
( 
from bk in db.Customers

// pay category 1
join tr in db.Payments
.Where(a => a.PDate <= thismonth && a.PDate >= thismonthstart && a.paycategory.Id == 1 && a.Paid=true)
on bk.CustomerID equals tr.CustomerID into trs

// pay category 2 
join tr2 in db.Payments
.Where(a => a.PDate <= thismonth && a.PDate >= thismonthstart && a.paycategory.Id == 2 && a.Paid=true)
on bk.CustomerID equals tr2.CustomerID into trs2
        ......
  etc to the 25 payment categories.
   }

select new LedgerViewModel
 {
 food=(int?)trs.Sum(c => c.Pay) ?? 0, 
 fuel=(int?)trs.Sum(c => c.Pay) ?? 0
 .. etc
   });
  return query.AsEnumerable();
    }

0 个答案:

没有答案