【问题标题】:Iconvertible Issue with dapper C#dapper C#的Iconvertible问题
【发布时间】:2017-09-08 15:11:46
【问题描述】:

需要帮助!

我试图使用 Dapper 从数据库中获取一个值,但是当我执行查询 指令时,我收到“对象必须实现 Iconvertible”异常。我做错了什么以及如何解决?

当我调用 Decrypt 方法并调用 ExceuteQuery 函数时发生错误。

代码

计划

ServiceSettingsEntity appSetting = MainRepository.GetConfigSettings(appSettingKey.ToString(), companyCode);


if (appSetting.IsEncrypted)
    appSetting.Value = MainRepository.Decrypt(appSetting.Value);
    return appSetting.Value.Trim();

解密功能

public static string Decrypt(string encryptedData)
{

    CommandSettings commandSettings = new CommandSettings
    {
        CommandText = @"[Utility].[DecryptData]",
        CommandType = CommandType.StoredProcedure,
        Parameters = new
                        {
                          @DataToDecrypt = encryptedData
                        }};

    return new MsSqlProviderBase(EdxDbConnectionString, 
                 commandSettings).ExecuteQuery<string>().FirstOrDefault();
}

ExecuteQuery 函数用于封装 dapper Query 函数

public List<T> ExecuteQuery<T>()
{
    using (IDbConnection dbConnection = DbConnection)
    {
        List<T> qResult = dbConnection.Query<T>(CommandSettings.CommandText, 
                             CommandSettings.Parameters,                     
                             commandTimeout: CommandSettings.CommandTimeout,
                             commandType: 
                                CommandSettings.CommandType).ToList();

return qResult;
    }
} 

【问题讨论】:

  • 您确定Utility.DecryptData 返回varchar?如果是 varbinary,则底层 .NET 类型(取决于在 Dapper 下运行的 IDbConnection 提供程序)可能是 byte[]
  • 嗨!是的,它是一个 varbinary,但我将它转换为字符串。

标签: c# orm dapper


【解决方案1】:

(基于 cmets 中的扩展信息。)大多数 IDbConnection 实现将(正确地)将 SQL varbinary“翻译”为 C# byte[]byte[]string 不能立即转换,因为 natural language text is complex

在底层存储过程可用之前,您需要将string 转换为byte[],反之亦然。

Microsoft Docs。结果:选择编码后,您将使用GetBytes(string)GetString(byte[]) 方法对进入和离开存储过程的文本进行编码/解码。

【讨论】:

    猜你喜欢
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多