Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

I have 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};
    }

I need to map CountryDTO to CountryModel, but through BaseCountryDTO class. I know that I can do it like this:

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

But I want to do it clear, something like this:

// This is not working code, just my imagination :)
            CreateMap<BaseCountryDTO, CountryModel>()
                .ForMember(model => model, dto => dto.Country));

Because in model can be more than 2 properties. Is there way to do it?

question from:https://stackoverflow.com/questions/65910732/c-sharp-how-to-map-inner-property-object-to-outer-class-with-automapper

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@LucianBargaoanu Helped me with the link https://docs.automapper.org/en/latest/Flattening.html#includemembers It solved my problem.

The solution looks like:

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

So the thing is we have to create a map of base class to our model with include of what we are really want to map. Then we should create a map of class which we are really need to map.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...