1
votes

I have my classes that looks like this :

public class Student{
    public string Name { get; set; }
    public string Id { get; set; }
    public List<Course> Courses { get; set; }
    public string Address { get; set; }
}

public class Course{
    public string Id { get; set; }
    public string Description { get; set; }
    public Date Hour { get; set; }
}

And i want to map the Student class to the following one using AutoMapper

public class StudentModel{
    public string Id { get; set; }
    public StudentProperties Properties { get; set; }
}

where StudentProperties is the remaining properties of the student class

public class StudentProperties{
    public string Name { get; set; }
    public List<Course> Courses { get; set; }
    public string Address { get; set; }
}

based on the AutoMapper documentation (https://github.com/AutoMapper/AutoMapper/wiki) we can use custom resolver to solve destination member while performing the mapping. But i don't want to add new class for the resolver.

I'm wondering if there is a simple way to perform the mapping by just doing simple configuration like this :

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Student, StudentProperties>();
    cfg.CreateMap<Student, StudentModel>();
});
3

3 Answers

2
votes

Here's one option that would work for you and would use AutoMapper for both StudentModel and StudentProperties:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Student, StudentProperties>();
    cfg.CreateMap<Student, StudentModel>()
        .ForMember(dest => dest.Properties,
            opt => opt.ResolveUsing(Mapper.Map<StudentProperties>));
});

Here, we're making use of ResolveUsing, but using the Func<> version in order to avoid creating a new class. This Func<> is just Mapper.Map itself, which already knows how to map from Student to StudentProperties.

1
votes

I think you can try to do something like that

CreateMap<Student, StudentModel>()
            .ForMember(dist => dist.Properties,
                opt => opt.MapFrom(src => Mapper.Map<StudentProperties>(src)))
0
votes
cfg.CreateMap<Student, StudentModel>()
    .ForMember(
        x => x.Properties,
        x => x.ResolveUsing((src) => {
            return new StudentProperties(){
                Name    = src.Name,
                Courses = src.Courses,
                Address = src.Address
            }));

Working Fiddle here.