Harsha W
Harsha W

Reputation: 3366

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

Upvotes: 0

Views: 1306

Answers (1)

Alex Marculescu
Alex Marculescu

Reputation: 5770

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

Upvotes: 3

Related Questions