简体   繁体   English

AutoMapper:使用包含的类创建一个地图

[英]AutoMapper: Create a map with included classes

I have these 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: 实现这些视图模型后,我使用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 the problem, that my property Personal in my SettingsViewModel is null. 现在我遇到了问题,我的SettingsViewModel属性Personal为null。 How can I combine my two mappings? 如何组合我的两个映射? How can I fill my Personal property with the data from my user object? 如何用我的用户对象中的数据填充我的Personal属性? In my user object, there are properties for FirstName und LastName . 在我的用户对象中,有FirstNameLastName属性。

You could set up your mapping 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're saying map the Personal property from the User object itself. 在这里,我们说的是从User对象本身映射Personal属性。 When you specify this, the mapping from UserPersonalViewModel will automatically be used. 指定时,将自动使用UserPersonalViewModel的映射。

Example: https://dotnetfiddle.net/YJnPDq 示例: https //dotnetfiddle.net/YJnPDq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM