command.Parameters.GetValue<long> 上的无效转换异常

Invalid cast exception on command.Parameters.GetValue<long>

我有一些 ADO.Net 代码如下,它在 DB 中成功执行了 SP,但它在 tenantId 处抛出异常,请指导我。

            command.Parameters.Input.BigInt(ParameterConstants.TenantId)
                                    .BigInt(ParameterConstants.PartyId, tenant.PartyId)
                                    .Varchar(ParameterConstants.TenantCode, tenant.TenantCode)
                                    .BigInt(ParameterConstants.PharmaId, tenant.PharmaId)
                                    .BigInt(ParameterConstants.UserId, userProfileId);

            command.ExecuteNonQuery();

            var tenantId = command.Parameters.GetValue<long>(ParameterConstants.TenantId);

var tenantId 它抛出转换异常 System.InvalidCastExceptio... 完全例外 Specified cast is not valid.

An exception of type 'System.InvalidCastException' occurred in ...Data.dll but was not handled in user code

Additional information: Specified cast is not valid.

我的猜测是 TenantId 的数据库类型和 class 类型不兼容。例如,string vs int vs long。

您的 GetValue<long> 方法可能无法处理 NULL 值。 GetValue<> 可能是您或其他人编写的自定义方法(不是 Microsoft),所以我不知道如何修复它。你可以试试:

var tenantId = command.Parameters.GetValue<long?>(ParameterConstants.TenantId);