Gerald Hughes
Gerald Hughes

Reputation: 6159

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

Upvotes: 1

Views: 203

Answers (2)

ThePerplexedOne
ThePerplexedOne

Reputation: 2950

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);

Upvotes: 3

RobPethi
RobPethi

Reputation: 571

Where you currently have

e.EducationEntryYear

Replace it with

e.EducationEntryYear == 0 ? System.DateTime.Now.Year : e.EducationEntryYear

Upvotes: 2

Related Questions