【发布时间】:2023-01-27 10:54:49
【问题描述】:
通过 AutoMapper,我想将 CreateUserInputModel 转换为 UserModel。
CreateUserInputModel 有一个属性:List<int> Options 接受选项的 ID。 UserModel 有一个属性:List<OptionModel> Options,其中包含OptionModel 的列表,其中的字段为Id。我尝试创建一个mapperForMember,但是当我将其添加到mapper中时,无一例外地出现异常错误。
如果您对如何解决此映射有任何想法,我将不胜感激。谢谢!
创建用户输入模型
public class CreateUserInputModel
{
public string Email { get; set; } = string.Empty;
public string Firstname { get; set; } = string.Empty;
public string Lastname { get; set; } = string.Empty;
public DateTime EmploymentDate { get; set; }
public int WorkTypeId { get; set; }
public List<int>? Options { get; set; } = new List<int>();
}
用户模型
public class UserModel
{
public int Id { get; set; }
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string Firstname { get; set; } = string.Empty;
public string Lastname { get; set; } = string.Empty;
public int VacationDays { get; set; }
public DateTime EmploymentDate { get; set; }
public WorkTypeModel WorkType { get; set; } = new WorkTypeModel();
public List<OptionModel>? Options { get; set; } = new List<OptionModel>();
}
用户映射器
CreateMap<UserModel, CreateUserInputModel>()
.ForMember(dest => dest.WorkTypeId, opt => opt.MapFrom(src => src.WorkType.Id))
.ForMember(dest => dest.Options, opt => opt.MapFrom(src => src.Options.Select(option => option.Id).ToList()))
.ReverseMap();
【问题讨论】:
标签: c# .net automapper