我正在尝试在我的Asp中使用AutoMapper。. NET 5 Core project.
在我的项目的Startup文件中,我添加了如下的
Type[] types = all scannable types...
services.AddAutoMapper((serviceProvider, MapperExpression) =>
{
// Not sure if this is needed
MapperExpression.ConstructServicesUsing(t => serviceProvider);
// Manually add the mapping without using a profile for now..
MapperExpression.CreateMap(typeof(User), typeof(UserViewModel));
}, types);
从上面,我期望能够将UserViewModel
映射到User
。但是,我得到了以下错误
AutoMapper。AutoMapperMappingException:缺少类型映射配置或不支持的映射。
映射类型:Object ->用户系统。对象- User
下面是我如何从控制器调用AutoMapper
[ApiController]
public class UsersController : ControllerBase
{
private readonly IMapper _mapper;
public UsersController(IMapper mapper)
{
_mapper = mapper;
}
public async Task<ActionResult<DisplayUserViewModel>> Create([FromBody] UserViewModel viewModel)
{
User model = _mapper.Map<User>(viewModel);
//...
}
}
这是我的模型
public class UserViewModel
{
[Required]
public string Password { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
}
public class User : IdentityUser<int>
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
如何正确地将AutoMapper服务添加到我的。net 5核心项目中?
需要做两件事:
-
在
Startup.cs
文件中:services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
-
您可以为您的映射创建一个文件夹,并将其命名为
MappingProfiles
或任何您想要的。然后添加映射配置文件类,注意,类应该继承AutoMapper
命名空间的Profile
对象,并在构造函数中进行映射。public class UserProfile : Profile { CreateMap<UserViewModel, User>(); }
在您的情况下,它不起作用是因为您做了错误的映射方向。
更改为:
MapperExpression.CreateMap(typeof(UserViewModel), typeof(User));