使用automapper的抽象类

时间:2011-10-13 01:44:05

标签: asp.net-mvc asp.net-mvc-3 automapper

我有一个基类:

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配置?

1 个答案:

答案 0 :(得分:7)

您可以使用ConstructUsing将实例化逻辑放在枚举值的基础上:

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