SGN SGN - 1 month ago 12
C# Question

How do I set a parameter based on a condition using LINQ and Entity framework

This is my code:

await ctx.Education.AsNoTracking()
.Where(e => e.EmployeeNumber == employeeNumber)
.Select(e => new EducationDTO {
Id = e.EducationID,
StartDate = DbFunctions.CreateDateTime(e.EducationEntryYear , 1, 1, 0, 0, 0) ?? DateTime.Now,
EndDate = DbFunctions.CreateDateTime(e.EducationGraduationYear, 1, 1, 0, 0, 0),
})
.ToListAsync().ConfigureAwait(false);


In some cases "e.EducationEntryYear" is 0, which as a result returns this exception
Conversion failed when converting date and/or time from character string.


What is the simplest way to have first parameter as current year, in case
e.EducationEntryYear
is 0

Answer

Use the conditional (?) operator.

await ctx.Education.AsNoTracking()
        .Where(e => e.EmployeeNumber == employeeNumber)
        .Select(e => new EducationDTO {
                Id = e.EducationID,
                StartDate =  DbFunctions.CreateDateTime(e.EducationEntryYear == 0 ? DateTime.Now.Year : e.EducationEntryYear, 1, 1, 0, 0, 0) ?? DateTime.Now,
                EndDate = DbFunctions.CreateDateTime(e.EducationGraduationYear, 1, 1, 0, 0, 0),
        })
        .ToListAsync().ConfigureAwait(false);