返回列表时,AutoMapper返回NULL

时间:2017-07-03 11:22:55

标签: automapper viewmodel datamodel

没有AutoMapper的代码:

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

我使用AutoMapper完成上述任务。但它返回NULL列表。请参考以下代码:

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

1 个答案:

答案 0 :(得分:0)

您不需要在列表之间定义映射,只需在对象之间定义,AutoMapper将知道如何推断:

Mapper.CreateMap<CountryDM, CountryVM>();

其余的保持不变