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?
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With