How can I send a string as NULL to SQLServer using Dapper?

前提是你 提交于 2019-12-06 18:24:49

问题


I've got a scenario where a string in C# can be null. I need it to be NULL on SQLServer.

I'm sending it to SQLServer using Dapper with a query like:

connection.Query<MyObject>("[dbo].[sp_MyStoredProcedure]"), new
{
    StartDate: startDate
}, commandType: CommandType.StoredProcedure);

Where startDate is the string that can sometimes be equal to null.

The stored procedure's parameter is

@StartDate varchar(10) = NULL

When it's is NULL it returns all records. I've confirmed this behavior works via SSMS.

I read this post by Marc Gravell that states:

The null vs DBNull issue is a constant cause of confusion; however, generally if people say null in C# they intend null in SQL. This is the approach that dapper adopts.

This leads me to believe that when the string is set to null, it should send DBNull.Value to SQLServer.

However, this doesn't appear to be the case. I get back 0 records from SQLServer when sending a null string. This seems indicative of sending an empty string, rather than a DBNull.Value.

Also, I can't send DBNull.Value directly:

connection.Query<MyObject>("[dbo].[sp_MyStoredProcedure]"), new
{
    StartDate: DBNull.Value
}, commandType: CommandType.StoredProcedure);

This produces an exception within Dapper:

The member StartDate of type System.DBNull cannot be used as a parameter value

Question

How can I send NULL to SQLServer, using Dapper, when I have a string in C# that can be null?


Important

Dapper does indeed send NULL when a string is null. This assumption was a mistake on my part based on faulty information. Nonetheless, this question may serve to help someone else who makes an equally faulty assumption.

Furthermore, the accepted answer provides a good mechanism for dealing with optional or conditional parameters.


回答1:


You can choose not to send StartDate.

Example:

dynamic parameters = new {

};

if (!string.IsNullOrWhiteSpace(startDate)) 
{
   parameters.StartDate = startDate;
}

connection.Query<MyObject>("[dbo].[sp_MyStoredProcedure]"), parameters, commandType: CommandType.StoredProcedure);

Edit:

Also, your stored procedure must accept nulls. Here's an example:

CREATE PROCEDURE [ExampleProc]
   @StartDate datetime = null
AS
   Select @StartDate



回答2:


Yes, dapper knows to replace reference-null with DBNull.Value whenever it sees it. Because DBNull is my arch -nemesis, and if I never see it again in my application code (library code is different) I will die a little happier.

See also: https://stackoverflow.com/a/9632050/23354



来源:https://stackoverflow.com/questions/21631263/how-can-i-send-a-string-as-null-to-sqlserver-using-dapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!