AutoMapper: create a map with included classes

I have two view models:

public class SettingsViewModel
{
    public string UserId { get; set; }
    public PersonalViewModel Personal { get; set; }
}

public class PersonalViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

      

After implementing these view models, I created a map with automapper:

    Mapper.CreateMap<User, PersonalViewModel>()
        .ForMember(vm => vm.Birthday, m => m.MapFrom(
            u => (u.Birthday.HasValue) ? u.Birthday.Value.ToString("dd.MM.yyyy") : DateTime.Now.ToString("dd.MM.yyyy")));

    Mapper.CreateMap<User, SettingsViewModel>()
        .ForMember(vm => vm.UserId, m => m.MapFrom(
            u => u.Id));

    var viewModel = Mapper.Map<User, SettingsViewModel>(user);

      

Now I have a problem that my property Personal

in mine SettingsViewModel

is null. How can I combine my two mappings? How can I populate my property with Personal

data from my custom object? My user object has properties for FirstName

und LastName

.

+3


source to share


1 answer


You can customize the display this way:

Mapper.CreateMap<User, SettingsViewModel>()
    .ForMember(vm => vm.UserId, m => m.MapFrom(u => u.Id))
    .ForMember(vm => vm.Personal, opt => opt.MapFrom(u => u));

      



Here we are talking map property Personal

from the object itself User

. When you specify this, the mapping from User

will be automatically used PersonalViewModel

.

Example: https://dotnetfiddle.net/YJnPDq

+1


source







All Articles