将automapper项目投影到更大的对象中 [英] automapper project into a larger object
问题描述
使用 Automapper ,是否可以将较小的对象投影到较大的对象上?
With Automapper, is it possible to project a smaller object onto a larger one?
例如,控制器接受数据作为ViewModel实例.然后,我需要在数据库中创建一条记录.因此,我将此视图模型投影到域模型上.在我将域模型实例填充到View Model数据后,我将在数据库中存储数据之前手动填充域模型中的其他字段.
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.
有可能这样做吗?
谢谢.
推荐答案
是的,这完全有可能.只需创建从ViewModel到域模型的映射,然后使用 Ignore()代码>
忽略不存在的属性:
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())
小例子:
public ActionResult Register(UserModel model)
{
User user = Mapper.Map<User>(model);
user.Password = PasswordHelper.GenerateHashedPassword();
_db.Users.Add(user);
_db.SaveChanges();
}
使用此配置的映射:
CreateMap<UserModel, User>()
.ForMember(dest => dest.Password, opt => opt.Ignore());
这可以确保密码不会被AutoMapper覆盖.
This makes sure that the password won't be overridden by AutoMapper.
这篇关于将automapper项目投影到更大的对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!