I have this code below working fine w/o the condition in the line payrollEndDate = p.PayrollEndDate.Value.Year >= 2016
because it gives me an error Invalid cast from 'Boolean' to 'DateTime'.
and the code that I added is return a boolean
var per = (from p in db.Periods select new { periodId = p.PeriodId, periodStart = p.StartDate, periodEnd = p.EndDate, payrollEndDate = p.PayrollEndDate.Value.Year >= 2016 });
var periods = (from p in per.AsEnumerable() select new { perId = p.periodId, PayrollEndDate = Convert.ToDateTime(p.payrollEndDate).ToShortDateString() }).AsQueryable();
ViewBag.PeriodEndDate = new SelectList(periods, "PayrollEndDate", "PayrollEndDate", null);
How to take the year 2016 onwards?
select
is for projections, not filtering. It sounds like you want a where
clause instead. I'd suggest not using query expressions here, given that you're only doing simple things:
var query = db.Periods
.Where(p => p.PayrollEndDate != null &&
p.PayrollEndDate.Value.Year >= 2016)
.AsEnumerable()
.Select(p => new {
p.PeriodId,
PayrollEndDate = p.PayrollEndDate.Value.ToShortDateString()
});
(I strongly suspect you don't actually want the AsQueryable()
call there... it may give the impression that any further querying will be done in the database, but that would be an illusion, given that you've got AsEnumerable()
already.)
I've removed the Convert.ToDateTime
call as I'm assuming p.PayrollEndDate.Value
is already a DateTime
.
See more on this question at Stackoverflow