c# - 无法映射 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; }
}
}
笔记:
我正在使用启用了可为空类型的 dotnet core 3.1
我不想使用构造函数或使用函数转换
我正在使用 Automapper v 10.0.0
解决方案
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));
推荐阅读
- caching - 什么是好的 javascript 异步初始化/缓存模式?
- java - Spring boot @MockBean 疏远行为
- java - 将方法 .equalsOr() 添加到 String 类
- git - 获取最近推送的提交的 github URL
- jquery - Load div each x second and allow scroll top
- django - Django filter query and or and
- mysql - MySQL:从相互关联的 3 个或 4 个表中获取最新的未读消息
- android - 为什么我的 OpenGL 纹理涂成粉红色?
- python - Python Matplotlib,茎图不适用于 FuncAnimation
- google-maps - Google Timezone API 的时区 id 是什么意思?