Search code examples
c#.netdapper

How to check for null values with Dapper


I'm having an SQL table Countries, with CountryId and StateId. StateId can be null, as not all countries have States. I'd like to check if the combination of country/state exists in the table. If I have the country "NL" and state NULL in the table, and I use the following query where countryId = "NL" and stateId = null:

return await conn.ExecuteScalarAsync<bool>(@"SELECT COUNT(*)
                                             FROM [dbo].[Countries]
                                             WHERE [CountryId] = @CountryId
                                             AND [StateId] = @StateId",
                                             new { countryId, stateId });

It will return false. I expected a true response. Could someone explain this behaviour and what is the best approach to solve this?


Solution

  • That is not a Dapper issue. Comparing anything to NULL with the = operator will usually return false. You will have to use "is null" for comparison, ie

    AND [StateId] is null
    

    (at least on SQL Server). That means of course that your query will have to look differently in case stateid is null.