2016-11-09 65 views
1

條件這是我的代碼:我設置的參數如何基於使用LINQ和Entity Framework

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

+0

替換它與'e.EducationEntryYear == 0只需更換'e.EducationEntryYear'? DateTime.Now.Year:e.EducationEntryYear' – itsme86

+0

你有沒有試過e.EducationEntryYear> 0?e.EducationEntryYear:2016? –

+0

您必須先將DateTime.Now.Year保存到變量中 –

回答

3

使用條件(?)運算符。

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

如果您目前有

e.EducationEntryYear 

e.EducationEntryYear == 0 ? System.DateTime.Now.Year : e.EducationEntryYear 
相關問題