问题
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