I am trying to use AutoMapper in Asp.Net Framework API (not core) and when I try to use, my model DTO gets all attributes null.
I tried a lot of solutions and a lots are deprecated. So, my actual solution is:
- Create a Configuration class
public static class AutoMapperConfig
{
public static IMapper _mapper { get; set; }
public static void Register()
{
var mapperConfig = new MapperConfiguration(
config =>
{
config.AddProfile<MyProfile>();
}
);
_mapper = mapperConfig.CreateMapper();
}
}
- Load at the start in Global.asax
protected void Application_Start()
{
...
AutoMapperConfig.RegisterMapping();
}
- Take model from .edmx and create a DTO
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Address { get; set; }
...
public string Email { get; set; }
}
public class UserDto
{
//I need only this 3
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
}
- Create a Profile
public class MyProfile : Profile
{
public MyProfile()
{
CreateMap<User, UserDto>().ReverseMap();
}
}
- Use AutoMapper in a Controller
public class MyController : ApiController
{
readonly IMapper mapper = AutoMapperConfig._mapper;
public List<UserDto> Get()
{
using(var ctx = new DbEntities())
{
var src = ctx.User.ToList;
var dst = new List<UserDto>();
src.ForEach(u = > dst.Add(mapper.Map<UserDto>(u)));
}
}
}
Now, for some kind of reason, I get all object in dst List null. For example, I have 3 object in DB and when I call this method I retrive 3 DTO objects but with all params null. Why?
Thanks