简体   繁体   English

如何使用 Dapper 检查 null 值

[英]How to check for null values with Dapper

I'm having an SQL table Countries, with CountryId and StateId.我有一个 SQL 表国家,带有 CountryId 和 StateId。 StateId can be null, as not all countries have States. StateId 可以是 null,因为并非所有国家/地区都有州。 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:如果我在表中有国家“NL”和 state NULL,我使用以下查询 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?有人可以解释这种行为吗?解决这个问题的最佳方法是什么?

That is not a Dapper issue.这不是 Dapper 的问题。 Comparing anything to NULL with the = operator will usually return false.使用 = 运算符将任何内容与 NULL 进行比较通常会返回 false。 You will have to use "is null" for comparison, ie您将不得不使用“is null”进行比较,即

AND [StateId] is null

(at least on SQL Server). (至少在 SQL 服务器上)。 That means of course that your query will have to look differently in case stateid is null.这当然意味着如果 stateid 是 null,您的查询必须看起来不同。

Check this:检查这个:

SELECT COUNT(*)
       FROM [dbo].[Countries]
       WHERE [CountryId] = @CountryId
       AND ([StateId] IS NULL OR ([StateId] IS NOT NULL AND [StateId] = @StateId))

It will check if StateId is null , then only the 'CountryId' will be checked for those countries with no state, if StateId is not null , then StateId would be checked too它将检查StateId是否为null ,然后只检查没有 state 的国家的“CountryId”,如果StateId不是null ,则也将检查StateId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM