我正在尝试使用 Dapper 从数据库中获取值,但是当我执行 query<> 指令时,我收到“对象必须实现 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函数用于封装短小精悍的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;
}
}
(基于评论中的扩展信息。)大多数
IDbConnection
实现将(正确地)将 SQL varbinary
“翻译”为 C# byte[]
。 byte[]
和 string
不能立即转换,因为 自然语言文本很复杂。
在底层存储过程可用之前,您需要使用编码将
string
转换为 byte[]
,反之亦然。
请参阅 Microsoft 文档。结果:选择编码后,您将使用
GetBytes(string)
和 GetString(byte[])
方法对进入和离开存储过程的文本进行编码/解码。