gpt4 book ai didi

asp.net-mvc - 带有自动映射器的抽象类

转载 作者:行者123 更新时间:2023-12-02 07:44:55 25 4
gpt4 key购买 nike

我有一个基类:

public abstract class User
{
/* properties */
}

public class Teacher : User
{

}

public class Student : User
{

}

然后我想根据属性将我的 View 模型映射到这些子类之一:

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

最佳答案

您可以使用 ConstructUsing 根据枚举值放置实例化逻辑:

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

关于asp.net-mvc - 带有自动映射器的抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7748517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com