【问题标题】:AutoMapper returns NULL when returning a listAutoMapper 返回列表时返回 NULL
【发布时间】:2017-12-06 15:32:38
【问题描述】:

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

【问题讨论】:

    标签: c# automapper viewmodel datamodel


    【解决方案1】:

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

    Mapper.CreateMap<CountryDM, CountryVM>();
    

    其余的保持不变

    【讨论】:

    • List&lt;CountryDM&gt; countryDMList = _partyManagerRepo.GetCountry(); List&lt;CountryVM&gt; countryVMList = new List&lt;CountryVM&gt;(); Mapper.CreateMap&lt;CountryDM,CountryVM&gt;(); Mapper.Map&lt;List&lt;CountryDM&gt;&gt;(countryVMList); return countryVMList; 这也将NULL 返回到countryVMList
    猜你喜欢
    • 1970-01-01
    • 2015-08-20
    • 2018-05-29
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 2019-08-31
    相关资源
    最近更新 更多