How to pass a null parameter with Dapper

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

I have a stored procedure that has a parameter with no default value, but it can be null. But I can't figure out how to pass null with Dapper. I can do it just fine in ADO.

connection.Execute("spLMS_UpdateLMSLCarrier", new { **RouteId = DBNull.Value**, CarrierId = carrierID, UserId = userID, TotalRouteRateCarrierId = totalRouteRateCarrierId },                                         commandType: CommandType.StoredProcedure); 

Exception:

System.NotSupportedException was caught   Message=The member RouteId of type System.DBNull cannot be used as a parameter value   Source=Dapper   StackTrace:        at Dapper.SqlMapper.LookupDbType(Type type, String name) in C:\Dev\dapper-git\Dapper\SqlMapper.cs:line 348        at Dapper.SqlMapper.CreateParamInfoGenerator(Identity identity) in C:\Dev\dapper-git\Dapper\SqlMapper.cs:line 1251        at Dapper.SqlMapper.GetCacheInfo(Identity identity) in C:\Dev\dapper-git\Dapper\SqlMapper.cs:line 908        at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType) in C:\Dev\dapper-git\Dapper\SqlMapper.cs:line 532        at Rating.Domain.Services.OrderRatingQueueService.UpdateLMSLCarrier(Int32 totalRouteRateCarrierId, Int32 carrierID, Int32 userID) in C:\DevProjects\Component\Main\Source\Rating\Source\Rating.Domain\Services\OrderRatingQueueService.cs:line 52        at Benchmarking.Program.OrderRatingQueue() in C:\DevProjects\Component\Main\Source\Benchmarking\Source\Benchmarking\Program.cs:line 81        at Benchmarking.Program.Main(String[] args) in C:\DevProjects\Component\Main\Source\Benchmarking\Source\Benchmarking\Program.cs:line 28   InnerException:  

Can't leave the RouteId off, gives me an error that says it's required. Can't use regular null either gives me another error. Can't change the stored procedure, it does not belong to me.

回答1:

I think you should be able to do it by casting null to the appropiate type. Let's assume RouteId is an integer:

connection.Execute("spLMS_UpdateLMSLCarrier", new { RouteId = (int?)null, CarrierId = carrierID, UserId = userID, TotalRouteRateCarrierId = totalRouteRateCarrierId }, commandType: CommandType.StoredProcedure); 

The problem you are encountering when using regular null is likely that the compiler cannot infer the type of RouteId in the anonymous type when just using null without the cast.



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