【发布时间】:2019-06-16 18:31:32
【问题描述】:
我正在编写一个 Web API,想将 User 模型映射到 UserView 模型。调试确认 mapper.Map(user) 返回空值对象。 mapper 是 AutoMapper 的 IMapper 类的一个实例。
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public UserRole? Role { get; set; }
}
public class UserView
{
public Guid Id { get; }
public string Name { get; }
public string Email { get; }
public UserRole? Role { get; }
}
public class MappingProfiles : Profile
{
public MappingProfiles()
{
CreateMap<User, UserView>();
}
}
//In startup.cs
services.AddAutoMapper();
//In user service class.
var userView = _mapper.Map<UserView>(user);
输出如下所示。
{
"id": "00000000-0000-0000-0000-000000000000",
"name": null,
"email": null,
"role": null
}
【问题讨论】:
-
使用 .ForMember(x => x.Password, q => q.Ignore())
-
UserView只有属性获取器,您希望它们如何填充。 -
自动实现的属性必须同时定义 get 和 set 访问器。参考这个帖子here
-
这是通过constructor mapping完成的。
标签: c# asp.net-core entity-framework-core automapper