Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 971
Shawn Mclean Avatar asked Jul 06 '26 04:07

Shawn Mclean


1 Answers

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();
    });
like image 180
Darin Dimitrov Avatar answered Jul 09 '26 16:07

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!