这是我的代码:

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


在某些情况下,“ e.EducationEntryYear”为0,结果返回此异常Conversion failed when converting date and/or time from character string.

如果e.EducationEntryYear为0,将第一个参数作为当前年份的最简单方法是什么

最佳答案

使用条件(?)运算符。

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

08-17 23:36