A Null Request Dapper.net still returns a Null Reference Exception with FirstOrDefault ()

I would like to return max Id from a table using Dapper.net

var x = connection.Query<int>("SELECT max(val) FROM info").FirstOrDefault();

This works - if the row does not exist, I get

The reference to the object is not installed in the instance of the object.

Does the value "OrDefault" mean that it returns 0 if there are no records?

How can I return 0 - or some non-zero value to prevent a failure.

THX

+4
source share
2 answers

The problem is that you are telling Dapper to wait for the sequence int, but in fact you have the possibility of meaning null. Therefore you need to either change the type

var x = connection.Query<int?>("SELECT max(val) FROM info").Single() ?? 0;

null.

var x = connection.Query<int>("SELECT COALESCE(max(val), 0) FROM info").Single();

Single , .

FirstOrDefault, , , .

+7
var x = connection.Query<int>("SELECT ISNULL(max(val), 0) FROM info").Single();

ISNULL, , null.

+1

Source: https://habr.com/ru/post/1658818/


All Articles