将AutoMapper与Data Reader一起使用 [英] Using AutoMapper with Data Reader

查看:85
本文介绍了将AutoMapper与Data Reader一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历了如何轻松地将DataReader转换为List< T> ;?

我想实现上面链接中被接受为答案的东西.

I wanted to implement something like what is accepted as an answer in the above link.

场景:

我正在使用OdbcDataReader从数据库中检索.

I am using OdbcDataReader to retrieve from the database.

我有一个Model Class.仅供参考,此类的属性是数据库中列名称的精确副本.我需要将这些列映射到属性并返回List 可以使用Automapper来完成.

And I have a Model Class . FYI , the properties of this class are exact replica of the column names from the database. I need to map these columns to the properties and return List Can this be accomplished using Automapper.

推荐答案

类似这样的东西

public List<T> ReadData<T>(string queryString)
{
    using (var connection = new SqlConnection(constr))
        using (var command = new SqlCommand(queryString, connection))
        {
            connection.Open();
            using (var reader = command.ExecuteReader())
                if (reader.HasRows)
                    return Mapper.DynamicMap<IDataReader, List<T>>(reader);
        }

    return null;
}

定义班级

public class MarkType
{
    public int id { get; set; }
    public string name { get; set; }
    public DateTime inserted { get; set; }
}

使用

List<MarkType> lst = _helper.ReadData<MarkType>("SELECT [id],[name],[inserted] FROM [marktype]");

这篇关于将AutoMapper与Data Reader一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆