[英]C# How to map inner property object to outer class with AutoMapper?
我有 3 節課:
public class CountryModel
{
public int Id { get; set; }
public string Title { get; set; }
}
public class CountryDTO
{
public int Id { get; set; }
public string Title { get; set; }
}
public class BaseCountryDTO
{
public CountryDTO Country {get; set};
}
我需要 map CountryDTO 到 CountryModel,但通過 BaseCountryDTO class。 我知道我可以這樣做:
CreateMap<BaseCountryDTO, CountryModel>()
.ForMember(model => model.Id, o => o.MapFrom(dto => dto.Country.Id))
.ForMember(model => model.Title, o => o.MapFrom(dto => dto.Country.Title));
但我想清楚,像這樣:
// This is not working code, just my imagination :)
CreateMap<BaseCountryDTO, CountryModel>()
.ForMember(model => model, dto => dto.Country));
因為在 model 中可以有 2 個以上的屬性。 有辦法嗎?
如果CountryModel
和CountryDTO
中的屬性具有相同的名稱/類型,那么您可以簡單地將映射配置為 -
CreateMap<CountryDTO, CountryModel>();
您可以將映射測試為 -
CountryDTO dto = new CountryDTO { Id = 4, Title = "Something" };
CountryModel model = Mapper.Map<CountryModel>(dto);
它會自動 map 從CountryDTO
到CountryModel
的屬性,無論它們有多少。 您不必手動配置任何屬性的映射,或者 go 通過另一個 class (如BaseCountryDTO
。
@LucianBargaoanu通過鏈接幫助我解決了我的問題。
解決方案如下所示:
CreateMap<BaseCountryDTO, CountryModel>().IncludeMembers(s => s.Country);
CreateMap<CountryDTO, CountryModel>();
所以問題是我們必須創建一個基礎 class 的 map 到我們的 model ,其中包含我們真正想要的 Z1AEZ18B85DC8ED51FE24490511 然后我們應該創建一個 map 的 class ,這是我們真正需要的 map。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.