1. 程式人生 > 其它 >linq Nullable object must have a value

linq Nullable object must have a value

異常描述

System.InvalidOperationException
  HResult=0x80131509
  Message=Nullable object must have a value.
  Source=System.Private.CoreLib
  StackTrace:
   at System.ThrowHelper.ThrowInvalidOperationException_InvalidOperation_NoValue()
   at System.Nullable`1.get_Value()
   at YiSha.Service.SystemManage.KpiRewordsService.
<>c__DisplayClass3_1.<GetGrapeChartByUser>b__15(<>f__AnonymousType9`8 o) in D:\codes\GrapeChart\YiSha.Business\YiSha.Service\SystemManage\KpiRewordsService.cs:line 190 at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Func`2 predicate, Boolean& found) at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`
1 source, Func`2 predicate) at YiSha.Service.SystemManage.KpiRewordsService.GetGrapeChartByUser(Int64 user) in D:\codes\GrapeChart\YiSha.Business\YiSha.Service\SystemManage\KpiRewordsService.cs:line 190 at YiSha.Business.SystemManage.KpiRewordsBLL.GetGrapeChartByUser(Int64 user) in D:\codes\GrapeChart\YiSha.Business\YiSha.Business\SystemManage\KpiRewordsBLL.cs:line 99
at YiSha.Admin.Web.Controllers.HomeController.UserDashboard(String id) in D:\codes\GrapeChart\YiSha.Web\YiSha.Admin.Web\Controllers\HomeController.cs:line 84 at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()

解決

在linq的select中 

方案1: 將DateTime 或者 int 等型別改成Datetime?  int?

方案2: ColumnName =  table == null ? null : (datetime?)table.column 

在lambda的FirstOrDefault中

使用 table.Where(p=> p.column  != null).FirstOrDefault(o => o.column  == value);