我有一个基类:
public abstract class User
{
/* properties */
}
public class Teacher : User
{
}
public class Student : User
{
}
然后我想基于属性将我的视图模型映射到这些子类中的一个:
public enum UserType
{
Teacher,
Student
}
public class UserVM
{
/* Properties of User */
public UserType UserType {get; set;}
}
基于UserVM.UserType,我想映射到相关的子类:
userModel.UserType = UserType.Teacher;
//user will be of type Teacher
var user = Mapper.Map<UserVM, User>(userModel);
如何为此设置CreateMap
配置?
答案 0 :(得分:7)
您可以使用ConstructUsing
将实例化逻辑放在枚举值的基础上:
Mapper
.CreateMap<UserVM, User>()
.ConstructUsing(userVM =>
{
if (userVM.UserType == UserType.Teacher)
{
return new Teacher();
}
return new Student();
});