Abstract classes with automapper
I have a base class:
public abstract class User
{
/* properties */
}
public cla开发者_如何转开发ss 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();
});
精彩评论