Neil Walker
Neil Walker

Reputation: 6858

automapper returning empty list but reflection works fine

I am reading from a data reader and want to automap into a list of objects, however while it is working fine using basic reflection, I always get an empty list using Automapper.

This is my code using reflection that works:

List<T> res = new List<T>();
using (var cmd = new OleDbCommand("Select ID, THP, Parent FROM Node_DP", conn))
            {
                conn.Open();
                using (var reader = cmd.ExecuteReader())
                {
                    if(reader.HasRows)
                    {
                     while (reader.Read())
                     {
                        T t = new T();

                        for (int inc = 0; inc < reader.FieldCount; inc++)
                        {
                            Type type = t.GetType();
                            PropertyInfo prop = type.GetProperty(reader.GetName(inc));
                            prop.SetValue(t, reader.GetValue(inc), null);
                        }

                        res.Add(t);
                    }
                  }
                }
            }

Using automapper I do the following:

        var config = new MapperConfiguration(cfg =>
          {
              cfg.CreateMap<DbDataReader, List<T>>();
          });

        var res2 = iMapper.Map<DbDataReader, List<T>>(reader);

[EDIT] I downloaded Automapper.Data package and changed my code to:

        var config = new MapperConfiguration(cfg =>
          {
              cfg.AddDataReaderMapping();
              cfg.CreateMap<DbDataReader, List<T>>();
          });

My class has instance variables with the same case as the select statement.

What is wrong?

Upvotes: 1

Views: 800

Answers (1)

Akos Nagy
Akos Nagy

Reputation: 4360

Support for automated mapping of DataReader content was removed from the core package as of 4.0 and moved to Automapper.Data. Take a look at the how-to.

EDIT Here's a working sample code for the Northwind database:

public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
}
public class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddDataReaderMapping();                
            cfg.CreateMap<IDataReader, Category>();
        });

        using (var conn = new SqlConnection(@"Data Source=(localdb)\mssqllocaldb;Initial Catalog=Northwind;Integrated Security=True"))
        using (var cmd = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories", conn))
        {
            conn.Open();
            using (var reader = cmd.ExecuteReader())
            {                    
                var res2 = Mapper.Map<IDataReader, List<Category>>(reader);
            }
        }            
    }
}

Upvotes: 1

Related Questions