Linq Max: The cast to value type 'System.Decimal' failed because the materialized value is null

时间:2017-08-30 20:55:30

标签: c# linq

I have a simple LINQ that gets the max value from table

undefined

It works fine when table has at least one record, but when table is empty it returns The cast to value type 'System.Decimal' failed because the materialized value is null

Now my question is: how to check on just one Linq if the table has records an return the max id?.

2 个答案:

答案 0 :(得分:3)

您可以使用DefaultIfEmpty,在您的情况下值为1。类似的东西:

dbContext.My_Tasks.Select(m => m.TaskId).DefaultIfEmpty(1).Max()

如果没有任务,这将生成一个值为1的集合,而{1}}为1,则为1。

答案 1 :(得分:1)

Cast it to a public function handle(Request $request, Closure $next) { $request->server->set('HTTP_ACCEPT', 'application/json'); $request->headers = new HeaderBag($request->server->getHeaders()); return $next($request); } before self.counting it:

self.max