0

I'm using AutoMapper plugin to map DataTable to C# Object. Here is my Code:

public List<MyDto> GetReport()
{
    List<MyDto> list = null;
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<IDataReader, List<MyDto>>();
    });
    IMapper mapper = config.CreateMapper();
    list = mapper.Map<IDataReader, List<MyDto>>(Odao.Inst.GetReport().Tables[0].CreateDataReader()).ToList();
    return list;
}

My MyDto class looks like this

public class MyDto
{
     public int EmployeeId { get; set; }
     public string FullName { get; set; }
}

Here, data is properly returning from my DataAccess Layer but when It maps to Object, list is coming as empty. Am I missing anything here?

55SK55
  • 621
  • 2
  • 8
  • 23
  • Can't you use NHibernate to get data from the database? Something like `list = sessionService.GetDefaultSession().Query()`. As far as I know you can't get data from a database with AutoMapper, or am I wrong? –  Nov 12 '18 at 09:42
  • Data is returning using this line. `Odao.Inst.GetReport().Tables[0]` but, this data to Object mapping is not working – 55SK55 Nov 12 '18 at 09:46
  • What if you try `cfg.CreateMap>().ReverseMap()` just to see what happens? –  Nov 12 '18 at 09:51
  • No luck with `cfg.CreateMap>().ReverseMap()` – 55SK55 Nov 12 '18 at 09:53
  • 2
    https://github.com/AutoMapper/AutoMapper.Data/ – Lucian Bargaoanu Nov 12 '18 at 09:53
  • What if you change mapping to `cfg.CreateMap();` and then `list = mapper.Map(Odao.Inst.GetReport().Tables[0].CreateDataReader()).ToList();`? That's what I'd try next. So maybe there is a problem with automapper and that list. –  Nov 12 '18 at 09:57
  • Maybe this helps - https://stackoverflow.com/questions/25681102/using-automapper-with-data-reader - notice the comments on the answer – Rand Random Nov 12 '18 at 10:17

1 Answers1

1

I solved this by using AutoMapper ver 3.3.1. Basically, version 4 and above will not support this IDataReader functionality.

Now, the following code is working for me.

Mapper.Reset();
Mapper.CreateMap<IDataReader, MyDto>();
list = Mapper.Map<IDataReader,List<MyDto>>(Odao.Inst.GetReport().Tables[0].CreateDataReader()).ToList(); 
55SK55
  • 621
  • 2
  • 8
  • 23