Using AutoMapper with a Data Reader

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

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

Scenrio:

I am using OdbcDataReader to retrieve from a database.

And I have a model class. FYI, the properties of this class are an exact copy of the column names from the database. I need to map these columns to properties and return a list. This can be done using Automapper.

+6
source share
1 answer

Something like that

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

Using

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

Source: https://habr.com/ru/post/974875/


All Articles