Shawn Mclean
Shawn Mclean

Reputation: 57469

Abstract classes with automapper

I have a base class:

public abstract class User
{
    /* properties */
}

public class Teacher : User
{

}

public class Student : User
{

}

Then I want to map my view model to one of these child class base on a property:

public enum UserType
{
    Teacher,
    Student
}

public class UserVM
{
    /* Properties of User */
    public UserType UserType {get; set;}
}

Based on UserVM.UserType, I'd like to map to the related child class:

userModel.UserType = UserType.Teacher;
//user will be of type Teacher
var user = Mapper.Map<UserVM, User>(userModel);

How do I setup my CreateMap configurations for this?

Upvotes: 3

Views: 3174

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You could use the ConstructUsing where you would put the instantiation logic based on the value of the enum:

Mapper
    .CreateMap<UserVM, User>()
    .ConstructUsing(userVM =>
    {
        if (userVM.UserType == UserType.Teacher)
        {
            return new Teacher();
        }
        return new Student();
    });

Upvotes: 9

Related Questions