如何解决C#如何使用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};
}
我需要将 CountryDTO 映射到 CountryModel,但通过 BaseCountryDTO 类。 我知道我可以这样做:
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));
因为在模型中可以有 2 个以上的属性。有办法吗?
解决方法
如果 CountryModel
和 CountryDTO
中的属性具有相同的名称/类型,那么您可以简单地将映射配置为 -
CreateMap<CountryDTO,CountryModel>();
您可以将映射测试为 -
CountryDTO dto = new CountryDTO { Id = 4,Title = "Something" };
CountryModel model = Mapper.Map<CountryModel>(dto);
它会自动将属性从 CountryDTO
映射到 CountryModel
,无论它们有多少。您不必为任何属性手动配置映射,也不必通过其他类(如 BaseCountryDTO
)。
@LucianBargaoanu 帮我链接 https://docs.automapper.org/en/latest/Flattening.html#includemembers 它解决了我的问题。
解决方案如下:
CreateMap<BaseCountryDTO,CountryModel>().IncludeMembers(s => s.Country);
CreateMap<CountryDTO,CountryModel>();
所以问题是我们必须创建一个基类映射到我们的模型,其中包含我们真正想要映射的内容。然后我们应该创建一个我们真正需要映射的类的映射。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。