C# 如何使用 AutoMapper 将内部 属性 对象映射到外部 class?

C# How to map inner property object to outer class with AutoMapper?

我有 3 个 classes:

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

因为在模型中可以有 2 个以上的属性。有办法吗?

如果CountryModelCountryDTO中的属性相同names/types,那么您可以简单地配置映射为-

CreateMap<CountryDTO, CountryModel>();

您可以测试映射为 -

CountryDTO dto = new CountryDTO { Id = 4, Title = "Something" };
CountryModel model = Mapper.Map<CountryModel>(dto);

它会自动映射从CountryDTOCountryModel的属性,不管它们有多少。您不必为任何 属性 手动配置映射,也不必通过另一个 class,例如 BaseCountryDTO

@LucianBargaoanu 帮我 link https://docs.automapper.org/en/latest/Flattening.html#includemembers 它解决了我的问题。

解决方案如下:

CreateMap<BaseCountryDTO, CountryModel>().IncludeMembers(s => s.Country);
CreateMap<CountryDTO, CountryModel>();

所以问题是我们必须创建一个基础映射 class 到我们的模型,其中包含我们真正想要映射的内容。然后我们应该创建我们真正需要映射的 class 的映射。