automapper project into a larger object

左心房为你撑大大i 提交于 2021-01-28 03:56:21

问题


With Automapper, is it possible to project a smaller object onto a larger one?

For example, a controller accepts data as a ViewModel instance. I would then need to create a record in a database. So I would project this View Model onto a Domain Model. Once I have a Domain Model instance populated with View Model data I would then manually populate the additional fields in the Domain Model before storing data in the database.

Is it possible to do so?

Thanks.


回答1:


Yes this is perfectly possible. Just create a mapping from the ViewModel to the domain model and use Ignore() to ignore non-existing properties:

.ForMember(dest => dest.PropertyOnDomainModel, opt => opt.Ignore()) 

Small example:

public ActionResult Register(UserModel model)
{
    User user = Mapper.Map<User>(model);    
    user.Password = PasswordHelper.GenerateHashedPassword();
    _db.Users.Add(user);
    _db.SaveChanges();
}

With this configured mapping:

CreateMap<UserModel, User>()
    .ForMember(dest => dest.Password, opt => opt.Ignore());

This makes sure that the password won't be overridden by AutoMapper.



来源:https://stackoverflow.com/questions/19661657/automapper-project-into-a-larger-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!