[英]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.