【问题标题】:AutoMapper, InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[System.Byte]' to type 'Google.Protobuf.ByteString'AutoMapper,InvalidCastException:无法将类型为 \'System.Collections.Generic.List`1[System.Byte]\' 的对象转换为类型 \'Google.Protobuf.ByteString\'
【发布时间】:2022-11-05 02:44:39
【问题描述】:

我是 AutoMapper 的新手。

我正在从数据库中检索 Ink Strokes 作为字节 [],然后尝试将它们序列化为 Google.ProtoBuf.ByteString。

我一直收到错误:

InvalidCastException:无法转换类型的对象 'System.Collections.Generic.List`1[System.Byte]' 输入 'Google.Protobuf.ByteString'。

这是我所拥有的:

在 Protobuf 文件中:

message LoadInkResponse {
    bytes Strokes  =1;
}

在我的域模型中:

public class LoadInkResponse
    {
        public byte[] Strokes { get; set; }
    }

最后,在 AutoMapperProfile.cs 中,

CreateMap<Model.Models.ProgressNotesModel.LoadInkResponse, LoadInkResponse>()
   .ForMember(dest => dest.Strokes, opt => opt.MapFrom(src => ByteString.CopyFrom(src.Strokes)));

其中 ByteString.CopyFrom 来自 Google.Protobuf 程序集。

我将域 byte[] 转换为 DTO ByteString 的所有尝试都失败了,并显示相同的错误消息。

这是怎么做到的????

TIA。

【问题讨论】:

  • 升级 AutoMapper。
  • @LucianBargaoanu 我有一年前发布的版本。我需要有关映射转换的帮助。谢谢。
  • 您的映射的问题在于您使用的是值解析器,而实际上类型转换器更适合。

标签: protocol-buffers automapper


【解决方案1】:

对于来到这里的任何人,@Lucian Bargaoanu 是正确的。我使用“ForMember”值解析器的所有尝试都失败了。

但是,创建这个简单的类型转换器是可行的。

public class ByteStringTypeConverter : ITypeConverter<byte[], ByteString>
    {
        public ByteString Convert(byte[] source, ByteString destination, ResolutionContext context)
        {
            return ByteString.CopyFrom(source);
        }
    }

 CreateMap<byte[], ByteString>().ConvertUsing(new ByteStringTypeConverter());
 CreateMap<Model.Models.ProgressNotesModel.LoadInkResponse, LoadInkResponse>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多