我正在尝试使用Mapster将服务模型映射到视图模型。
我的服务模型包含一个字符串列表。
My View Model 包含一个 RolesViewModel 类型的列表。
RolesViewModel 有一个名为 RoleName 的字符串属性。
下面是我的模型
public class UserViewModel
{
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
public List<RolesViewModel> Roles { get; set; } = new List<RolesViewModel>();
}
public class RolesViewModel
{
public RolesViewModel(string roleName)
{
RoleName = roleName;
}
public string RoleName { get; set; }
}
//Service Model
public class User
{
public string Email { get; set; }
public List<string> Roles { get; set; } = new List<string>();
}
//Service Return Model
public class ServiceResponse<T>
{
public bool Success { get; set; } = false;
public Data.Enums.Exception Exception { get; set; }
public T ResponseModel { get; set; }
/// <summary>
/// Allows Service Response <T> to be cast to a boolean.
/// </summary>
/// <param name="response"></param>
public static implicit operator bool(ServiceResponse<T> response)
{
return response.Success;
}
}
我应用映射的控制器中的行如下:
List<UserViewModel> viewModel = serviceResponse.ResponseModel.Adapt<List<UserViewModel>>();
最后是我的映射配置
public class Mapping : IRegister
{
public void Register(TypeAdapterConfig config)
{
config.NewConfig<Tracer, TracerViewModel>();
config.NewConfig<Asset, AssetViewModel>();
config.NewConfig<Project, ProjectViewModel>();
config.NewConfig<User, UserViewModel>();
config.NewConfig<RolesViewModel, string>();
}
}
为了尝试使映射正常工作,我尝试将映射配置更新为:
public class Mapping : IRegister
{
public void Register(TypeAdapterConfig config)
{
config.NewConfig<Tracer, TracerViewModel>();
config.NewConfig<Asset, AssetViewModel>();
config.NewConfig<Project, ProjectViewModel>();
config.NewConfig<User, UserViewModel>().Map(dest => dest.Roles.Select(t => t.RoleName.ToString()).ToList(), src => src.Roles);
config.NewConfig<UserViewModel, User>().Map(src => src.Roles, dest => dest.Roles.Select(t => t.RoleName.ToString()).ToList());
config.NewConfig<RolesViewModel, string>();
}
}
但我收到错误消息:“从 'System.String' 到 'ViewModels.RolesViewModel' 的无效转换。
谁能告诉我我的映射类需要什么配置。