IMapper.map()函数返回空值对象。自动映射器问题

时间:2019-01-23 08:13:22

标签: c# asp.net-core entity-framework-core automapper

我正在编写一个Web API,想要将User模型映射到UserView模型。调试确认mapper.Map(user)返回空值对象。映射器是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
}

1 个答案:

答案 0 :(得分:2)

UserView模型仅具有吸气剂。如果要使其保持只读状态,则可以执行以下操作

向UserView添加构造函数

public class UserView
{

   public Guid Id { get;  }
   public string Name{ get; }                                    
   public string Email { get;  }
   public UserRole? Role { get; }

   public UserView(Guid id, string name, string email, UserRole role)
   {
      Id = id;
      Name = name;
      Email = email;
      Role = role;
   }
}

还要调整映射配置文件

public class MappingProfiles : Profile
{
    public MappingProfiles()
    {
        CreateMap<User, UserView>()
          .ConstructUsing(src => new UserView(src.Id, src.Name, src.Email, src.UserRole));
    }
}

最简单的方法是将设置器添加到UserView的所有属性中。