Search code examples
c#automapperviewmodeldatamodel

AutoMapper returns NULL when returning a list


Code without AutoMapper:

List<CountryDM> countryDMList = _countryRepo.GetCountry();
List<CountryVM> countryVMList = new List<CountryVM>();
foreach (CountryDM countryDM in countryDMList)
{
    countryVMList.Add(CountryVM.ToViewModel(countryDM));
}
return countryVMList;

I used AutoMapper for the above task. But it returns a NULL list. Please refer the below code:

List<CountryDM> countryDMList = _countryRepo.GetCountry();
Mapper.CreateMap<List<CountryDM>, List<CountryVM>>();
List<CountryVM> countryVMList = new List<CountryVM>();
return Mapper.Map<List<CountryVM>>(countryDMList);

public class CountryDM
{
    public int ID { get; set; }
    public string CountryCode { get; set; }
    public string Description { get; set; }
}

public class CountryVM
{
    public int ID { get; set; }
    public string CountryCode { get; set; }
    public string Description { get; set; }
}

Solution

  • You don't need to define a mapping between lists, just between objects, AutoMapper will know how to extrapolate that:

    Mapper.CreateMap<CountryDM, CountryVM>();
    

    the rest stays the same