我正在尝试使用 Mapster 将服务模型映射到视图模型。
我的服务模型包含一个字符串列表。
我的视图模型包含 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’的转换无效。
有人可以告诉我我的映射类中需要什么配置吗?
您似乎试图在 Register 函数的最后一行中强制在字符串和对象之间进行直接映射。mapster 和其他对象到对象映射器的概念是它们将对象映射到其他对象。您无法将对象映射到 CLR 引用类型。要实现您想要做的事情,最好的方法是创建一个接收字符串并正确处理它的函数。
正如 Mapster 所说,当映射到字符串时,它将使用 ToString 或 Parse 来执行映射:
var s = 123.Adapt<string>(); //equal to 123.ToString();
var i = "123".Adapt<int>(); //equal to int.Parse("123");
因此您需要实现一个转换例程,告诉mapster如何从String解析为RolesViewModel。