【问题标题】:IMapper.map() function return null values object. Automapper issueIMapper.map() 函数返回空值对象。自动映射器问题
【发布时间】: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


【解决方案1】:

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));
    }
}

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

【讨论】:

    猜你喜欢
    • 2022-12-20
    • 2021-02-17
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多