Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
using (var ctx = new CompanyEmployees())
{
int minYear = ctx.OccupationHistories.Min(o => o.StartDate.Year);
int maxYear = ctx.OccupationHistories.Max(o => o.EndDate.HasValue ? o.EndDate.Value.Year : DateTime.Now.Year);
List<int> yearsList = Enumerable.Range(minYear, maxYear - minYear + 1).ToList();
List<int> monthList = Enumerable.Range(1, 12).ToList();
var qry1 = from y in yearsList
from m in monthList
select new DateTime(y, m, 1);
var firstDays = qry1.ToList();
var qry2 = from y in yearsList
from m in monthList
select new DateTime(y, m, DateTime.DaysInMonth(y, m));
var lastDays = qry2.ToList();
var qry = from s in
(
from o in ctx.OccupationHistories
join d in ctx.Divisions
on o.DivisionID equals d.Id
join p in ctx.Positions
on o.PositionID equals p.Id
from x in
(
from a in firstDays
join b in lastDays
on new { a.Year, a.Month } equals new { b.Year, b.Month }
select new
{
FirstDay = a,
LastDay = b
})
where DateTime.Compare(o.StartDate, x.LastDay) <= 0 &&
DateTime.Compare(o.EndDate.HasValue ? o.EndDate.Value : DateTime.Now, x.FirstDay) >= 0
orderby o.EmployeeID
select new
{
EmployeeId = o.EmployeeID,
Division = d.Name,
Position = p.Name,
Year = x.FirstDay.Year,
Month = x.LastDay.Month
})
group s by new { s.Division, s.Position, s.Year, s.Month } into g
orderby g.Key.Year, g.Key.Month, g.Key.Division, g.Key.Position
select new EmployeesCount
{
Division= g.Key.Division,
Position= g.Key.Position,
Year= g.Key.Year,
Month= g.Key.Month,
EmployeeCount = g.Count()
};
return qry.ToList();
Профайлер для Entity Framework