如何使用Dapper将字符串作为NULL发送到SQLServer?
我有一个场景,其中C#中的字符串可以为null
。 我需要它在SQLServer上为NULL
。
我正在使用Dapper将其发送到SQLServer,其查询如下:
connection.Query("[dbo].[sp_MyStoredProcedure]"), new { StartDate: startDate }, commandType: CommandType.StoredProcedure);
其中startDate
是有时可以等于null
的字符串。
存储过程的参数是
@StartDate varchar(10) = NULL
当它为NULL
它返回所有记录。 我已经确认这种行为可以通过SSMS实现。
我读过Marc Gravell的这篇文章说:
null vs DBNull问题是混淆的常见原因; 但是, 通常如果人们在C#中声明为
null
,则他们在SQL中打算使用null
。 这是小巧玲珑采用的方法。
这让我相信当string
设置为null
,它应该将DBNull.Value
发送到SQLServer。
但是,情况似乎并非如此。 我在发送null
字符串时从SQLServer返回0条记录。 这似乎表示发送一个空字符串,而不是DBNull.Value
。
另外,我无法直接发送DBNull.Value
:
connection.Query("[dbo].[sp_MyStoredProcedure]"), new { StartDate: DBNull.Value }, commandType: CommandType.StoredProcedure);
这会在Dapper中产生exception:
System.DBNull类型的成员StartDate不能用作参数值
题
当我在C#中有一个可以为null
的string
时,如何使用Dapper将NULL
发送到SQLServer?
重要
当字符串为null
时,Dapper确实发送NULL
。 基于错误的信息,这个假设是我的错误。 尽管如此,这个问题可能有助于帮助那些做出同样错误假设的其他人。
此外,接受的答案提供了处理可选或条件参数的良好机制。
您可以选择不发送StartDate。
例:
dynamic parameters = new { }; if (!string.IsNullOrWhiteSpace(startDate)) { parameters.StartDate = startDate; } connection.Query("[dbo].[sp_MyStoredProcedure]"), parameters, commandType: CommandType.StoredProcedure);
编辑:
此外,您的存储过程必须接受空值。 这是一个例子:
CREATE PROCEDURE [ExampleProc] @StartDate datetime = null AS Select @StartDate
是的,dapper知道在看到它时用DBNull.Value
替换reference- null
。 因为DBNull
是我的主要问题,如果我在我的应用程序代码中再也看不到它(库代码不同),我会更加快乐。
另见: https : //stackoverflow.com/a/9632050/23354