binary binary - 2 months ago 37
ASP.NET (C#) Question

Automapper cannot fill the properties

I use Automapper in an MVC project where I also use ASP.NET Identity and inherit from ApplicationUser class to my custom user tables: Student and Coordinator. The problem is that; I retrieve User data and there is filled custom property in it (called Number), but after applying the Automappe's mapping, it only fills the properties in ApplicationUser and the Number property is null. Is there any mistake or how to fix it?

Domain Models:

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public string Name { get; set; }

public string Surname { get; set; }

//code omitted for brevity
}

public class Student: ApplicationUser
{
public int? Number { get; set; }
}


ViewModel:

public class RegisterViewModel
{
public int Id { get; set; }

public int? Number { get; set; }

//code omitted for brevity
}


Controller:

[AllowAnonymous]
[HttpGet]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}

ApplicationUser user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}

var config = new MapperConfiguration(cfg => {
cfg.CreateMap<ApplicationUser, RegisterViewModel>();
});

IMapper mapper = config.CreateMapper();
//var source = new ApplicationUser();
var dest = mapper.Map<ApplicationUser, RegisterViewModel>(user);

return PartialView("_Details", dest);
}

Answer

I wouldn't expect it to map Number. You're talking about two different types. If db.Users.Find(id); is an ApplicationUser then it won't work like you're showing because ApplicationUser does not have a Number Property.

If that object returned from db.Users.Find(id); is really a Student. Then cast it and do the mapping from Student

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Student, RegisterViewModel>()
        .ForMember(dest => dest.Id, opt => opt.Ignore());
});

Mapper.AssertConfigurationIsValid();

var myAppUser = new ApplicationUser();
var student = myAppUser as Student;
var appUserResult = Mapper.Map<RegisterViewModel>(student);
Comments