如何在SqlDataReader中使用AutoMapper.Data

时间:2016-02-01 12:29:39

标签: asp.net ado.net automapper


我正在尝试找到一个更新的示例,用于将 SqlDataReader 对象映射到自定义对象。

 Dim connectionString As String = ConfigurationUtil.ConnectionStrings("xxxx").ConnectionString
 Dim dr As SqlDataReader
 Dim a As AAAA
     Try
         Using cn As New SqlConnection(connectionString)
             Using cm As New SqlCommand
                 cm.Connection = cn
                 cn.Open()
                 cm.CommandType = CommandType.StoredProcedure
                 cm.CommandText = "qf.AAAAGet"
                 cm.Parameters.Add(New SqlParameter("@AAAAId", aaaaId))
                 Dim prmRV As New SqlParameter("@ReturnValue", SqlDbType.Int)
                 prmRV.Direction = ParameterDirection.ReturnValue
                 cm.Parameters.Add(prmRV)

                 dr = cm.ExecuteReader(CommandBehavior.SingleRow)

我想将 dr 映射到 ACustomObject (其中包含 dr 中返回的确切名称的所有字段)

  1. 我如何配置这样的映射器?
  2. 我如何调用地图?
  3. 我的想法是:
    - 在 Global.asax 中调用静态方法来执行init / config
    - 在我执行查询后进行映射。

    谢谢

1 个答案:

答案 0 :(得分:0)

在Global.asax中

你可以配置地图:

Mapper.Initialize(Sub(cfg)
                      MapperRegistry.Mappers.Add(New AutoMapper.Data.DataReaderMapper With { .YieldReturnEnabled = True })
                  End Sub)

Mapper.CreateMap(Of IDataReader, YourClass)

并且在exeucute代码中(结果为As IEnumerable(Of YourClass)):

Dim results = Mapper.Map(Of IDataReader, IEnumerable(Of YourClass))(dataReaderInstance)

满足您所有需求的帮助方法:

Class DataReaderMapper(Of YourClass)
    Shared Sub New()
        Mapper.Initialize(Sub(cfg) MapperRegistry.Mappers.Add(New AutoMapper.Data.DataReaderMapper() With { .YieldReturnEnabled = True }) 
        Mapper.CreateMap(Of IDataReader, YourClass)()
    End Sub

    Public Shared Function GetRecordes(reader As IDataReader) As IEnumerable(Of YourClass)
        Return Mapper.Map(Of IDataReader, IEnumerable(Of YourClass))(reader)
    End Function
End Class