开发者

Can AutoMapper map object to model property of the same type

I am attempting to improve my data flow between my MVC 3 Model and Views (mainly CRUD). I have taken the approach of using ViewModels and FormModels. My ViewModel contains everything it need to represent the view FormData, DropDownLists etc. The FormModel simply contains the FormData fields that are submitted by the form and are need开发者_如何学Pythoned to update a record.

My question is can I use AutoMapper to map UserDto information onto my FormData field in my ViewModel?

Obviously my mapping below is only mapping between the two object and not an object to property but I have tried using the ‘.ForMember’ mapping options but they are again for object members not an object to an object member. I have also looked at Custom Type Convertors but not sure if this is the right way to go.

Mapper.CreateMap<UserDto, UserViewModel>();
Mapper.CreateMap<UserViewModel, UserDto>();

public class UserViewModel
{
    public User FormData { get; set; }

    // DropDownLists

    // Other view specific data

}

public class UserFormModel
{
    public int UserId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Age { get; set; }

    [Required]
    public string Email { get; set; }
}

Any help would be much appreciated.


You need to create the map to the FormData property type and then tell AutoMapper to use this map.

(The following will likely not compile; I'm in the process of recreating my work machine and am working from memory).

Mapper.CreateMap<UserDto, User>(); // set up property mapping

Mapper.CreateMap<UserDto, UserViewModel>()
.ForMember(vm => vm.FormData, map => map.MapFrom(dto => Mapper.Map<UserDto, User>(dto)));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜