public class UserAppService : ApplicationService
{
private readonly IRepository<User> _userRepository;
public UserAppService(IRepository<User> userRepository)
{
_userRepository = userRepository;
}
public void CreateUser(CreateUserInput input)
{
var user = new User
{
Name = input.Name,
Surname = input.Surname,
EmailAddress = input.EmailAddress,
Password = input.Password
};
_userRepository.Insert(user);
}
}
通过 new 一个新的实体去赋值并保存数据,User 实体在现实的应用程序中会有更多的属性,这样的手动创建它会变得乏味且容易出错。当我们想要向 User 和 CreateUserInput 添加新属性时,我们还必须更改映射代码。
我们可以使用一个库来自动处理我们的映射。 AutoMapper是对象到对象映射的最佳库之一。ASP.NET Boilerplate 定义了一个IObjectMapper 接口来抽象它,然后使用Abp.AutoMapper 包中的 AutoMapper 实现这个接口。
public class UserAppService : ApplicationService
{
private readonly IRepository<User> _userRepository;
private readonly IObjectMapper _objectMapper;
public UserAppService(IRepository<User> userRepository, IObjectMapper objectMapper)
{
_userRepository = userRepository;
_objectMapper = objectMapper;
}
public void CreateUser(CreateUserInput input)
{
var user = _objectMapper.Map<User>(input);
_userRepository.Insert(user);
}
}
public void UpdateUser(UpdateUserInput input)
{
var user = _userRepository.Get(input.Id);
_objectMapper.Map(input, user);
}
[AutoMapTo(typeof(User))]
public class CreateUserInput
{
public string Name { get; set; }
public string Surname { get; set; }
public string EmailAddress { get; set; }
public string Password { get; set; }
}
[DependsOn(typeof(AbpAutoMapperModule))]
public class MyModule : AbpModule
{
public override void PreInitialize()
{
Configuration.Modules.AbpAutoMapper().Configurators.Add(config =>
{
config.CreateMap<CreateUserInput, User>()
.ForMember(u => u.Password, options => options.Ignore())
.ForMember(u => u.Email, options => options.MapFrom(input => input.EmailAddress));
});
}
}
[DependsOn(typeof(AbpAutoMapperModule))]
public class MyModule : AbpModule
{
public override void PreInitialize()
{
}
public override void Initialize()
{
var thisAssembly = typeof(MyModule ).GetAssembly();
IocManager.RegisterAssemblyByConvention(thisAssembly);
Configuration.Modules.AbpAutoMapper().Configurators.Add(
cfg => cfg.AddProfile<CustomDtoMapperProfile>()
);
}
}
public class CustomDtoMapperProfile : Profile
{
public CustomDtoMapperProfile()
{
CreateMap<CreateUserInput, User>()
.ForMember(u => u.Password, options => options.Ignore())
.ForMember(u => u.Email, options => options.MapFrom(input => input.EmailAddress));
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章