Using AutoMapper with Data Reader

两盒软妹~` 提交于 2020-01-12 19:08:54

问题


I went through How can I easily convert DataReader to List<T>?

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

Scenrio:

I am using OdbcDataReader to retrieve from the database.

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.


回答1:


Something like this

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;
}

Define your class

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

Use

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


来源:https://stackoverflow.com/questions/25681102/using-automapper-with-data-reader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!