0
votes

I was coding a web API, wanted to map User model to UserView model. Debugging confirms mapper.Map(user) returns null value object. mapper is an instance of IMapper Class of AutoMapper.

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

The output looks like this.

{
  "id": "00000000-0000-0000-0000-000000000000",
  "name": null,
  "email": null,
  "role": null
}
1
use .ForMember(x => x.Password, q => q.Ignore()) - CodeMan
UserView has only property getters, how do you expect them to be populated. - Ivan Stoev
Auto-implemented properties must define both get and set accessors. Refer to this post here - Chandan Rauniyar
This is done with constructor mapping. - Lucian Bargaoanu

1 Answers

2
votes

The UserView model only has getters. If you want to keep them readonly, you can do the following

Add a constructor to 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;
   }
}

Also adjust the mapping profile

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

The simplest way would be to add setters to all properties of UserView.