0

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
}
4
  • use .ForMember(x => x.Password, q => q.Ignore()) Commented Jan 23, 2019 at 8:21
  • 4
    UserView has only property getters, how do you expect them to be populated. Commented Jan 23, 2019 at 8:21
  • Auto-implemented properties must define both get and set accessors. Refer to this post here Commented Jan 23, 2019 at 8:34
  • This is done with constructor mapping. Commented Jan 23, 2019 at 9:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.