首页 > 解决方案 > 无法映射 byte[] 或 byte[]?(可为空的字节 [])使用 AutoMapper ForCtorParam 函数

问题描述

无法映射 byte[] 或 byte[]?(nullable byte[]) 使用 AutoMapper ForCtorParam 函数,我收到以下错误消息

AutoMapper.AutoMapperConfigurationException :找到未映射的成员。查看下面的类型和成员。添加自定义映射表达式、忽略、添加自定义解析器或修改源/目标类型对于没有匹配的构造函数,添加无参数 ctor、添加可选参数或映射所有构造函数参数 ======= ==================================================== ========================= Model -> ModelDto (Destination member list) AutoMapperForCtorParamTest+Model -> AutoMapperForCtorParamTest+ModelDto (Destination member list) 未映射的属性:代码链接ID

下面重新创建的示例代码

public class AutoMapperForCtorParamTest
    {
        private readonly IMapper mapper;

        public AutoMapperForCtorParamTest()
        {
            mapper = new Mapper(new MapperConfiguration(
                cfg =>
                    {
                        cfg.AddProfile<ModelMapperProfile>();
                    }));
        }

        [Fact]
        public void MapAllProperties()
        {
            mapper.ConfigurationProvider.AssertConfigurationIsValid();
        }

        public class ModelMapperProfile : Profile
        {
            public ModelMapperProfile()
            {
                var defaultCode = Guid.NewGuid().ToByteArray();

                CreateMap<Model, ModelDto>()
                    .ForCtorParam("type", cfg => cfg.MapFrom(x => 1))
                    .ForCtorParam("code", cfg => cfg.MapFrom<byte[]>(x => defaultCode))
                    .ForCtorParam("linkId", cfg => cfg.MapFrom<byte[]?>(x => null));
            }
        }

        public class ModelDto
        {
            public ModelDto(int id, string name, int type, byte[] code, byte[]? linkId)
            {
                Id = id;
                Name = name;
                Type = type;
                Code = code;
                LinkId = linkId;
            }

            public int Id { get; }

            public string Name { get; }

            public int Type { get; }

            public byte[] Code { get; }

            public byte[]? LinkId { get; }
        }

        public class Model
        {
            public Model(int id, string name)
            {
                Id = id;
                Name = name;
            }

            public int Id { get; }

            public string Name { get; }
        }
    }

笔记:

  1. 我正在使用启用了可为空类型的 dotnet core 3.1

  2. 我不想使用构造函数或使用函数转换

  3. 我正在使用 Automapper v 10.0.0

标签: c#automappermappernullable-reference-typesautomapper-6

解决方案


Use:

.ForCtorParam("text", opt => opt.MapFrom<byte[]?>(src => null));

In my case (string) I fixed it with:

.ForCtorParam("text", opt => opt.MapFrom<string>(src => null));

推荐阅读