Dapper 将 DbNull 转换为空字符串

问题描述 投票:0回答:1

我正在重构一些使用反射将 SqlCommand 映射到模型的代码。新代码使用 Dapper 框架并且工作得很好:

    Public Shared Function GetModel(Of T As New)(cmd As SqlCommand) As T
        Try

            Dim params = GetParametersDictionary(cmd)
            Dim result As Object

            Using conn As New SqlConnection(ConnectionString)
                result = conn.Query(Of T)(cmd.CommandText, params).FirstOrDefault()
            End Using

            Return result

        Catch ex As Exception
            ErrorsLogger.LogException(ex)
            Throw
        End Try
    End Function

但是,在旧代码中,我有字符串属性和 DbNull 值的边缘情况。比如:

    If IsTypeOfString(prop) AndAlso IsDbNull(value) Then
        prop.SetValue(obj, "")
    End If

新代码不会将 DbNull (NULL) 值转换为空字符串。相反,它不会设置值,即“Nothing”,从而破坏其他地方的一些代码。

所以我的问题是如何更改此函数以将 NULL 值转换为空字符串?最好没有反射。

尝试/考虑/限制的事情:

  • 自定义 Dapper SqlMapper:当值为 NULL 时不起作用。
  • 自定义模型映射器:无法为每种模型类型创建自定义模型映射器。
  • 在类构造函数中将字符串初始化为“”:无法保证每个字符串属性都使用“”正确初始化。
  • 无法更改查询或模型类。
c# .net vb.net dapper sqlcommand
1个回答
1
投票

Dapper 认为

null
""
是不同的东西,并积极尝试不将两者混为一谈。也许您可以对结果进行后处理。

© www.soinside.com 2019 - 2024. All rights reserved.