IMapper.map() function return null values object. Automapper issue

asp.net-core automapper c# entity-framework-core

Question

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
0
1/23/2019 10:54:17 AM

Accepted Answer

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.

2
1/23/2019 8:34:02 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow