Mapster映射问题。将对象列表映射到字符串列表

时间:2018-02-26 16:38:03

标签: c# mapping dto mapster

我正在尝试使用 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'的转换无效。

有人可以告诉我在我的映射类中需要什么配置。

2 个答案:

答案 0 :(得分:1)

您似乎正在尝试在Register函数的最后一行中强制字符串和对象之间的直接映射.Mapter和其他对象到对象映射器的概念是它们将对象映射到其他对象。您无法将对象映射到CLR引用类型。要实现您想要做的事情,最好的方法是创建一个接收字符串并正确处理它的函数。

答案 1 :(得分:0)

正如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。

相关问题