如何使用Dapper传递null参数

33 dapper

我有一个存储过程,其参数没有默认值,但可以为null.但我无法弄清楚如何使用Dapper传递null.我可以在ADO中做得很好.

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

例外:

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: 
Run Code Online (Sandbox Code Playgroud)

不能离开RouteId,给我一个错误,说明它是必需的.不能使用常规null或者给我另一个错误.无法更改存储过程,它不属于我.

dri*_*iis 64

我认为你应该能够通过转换null为适当的类型来实现.我们假设RouteId是一个整数:

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

使用常规null时遇到的问题很可能是在没有强制转换的情况下RouteId使用时,编译器无法推断出匿名类型的类型null.

  • @BarryDysert - 它会是(字符串)null - 字符串是引用类型,所以不需要或不支持?后缀,用于表示可为空的值类型. (3认同)