gpt4 book ai didi

c# - AutoMapper - 将空字符串映射到 int

转载 作者:行者123 更新时间:2023-12-02 15:01:00 25 4
gpt4 key购买 nike

我正在尝试使用 AutoMapper 转换 SourceThingDestinationThing

public class SourceThing
{
public string Length;
public string Width;
public string Make;
}

public class DestinationThing
{
public int Length;
public int Width;
public string Make;
}

CreateMap<SourceThing, DestinationThing>();

_mapper.Map<DestinationThing>(sourceObj);

我遇到的问题是当我的 sourceObj是以下内容:

{
"Length": "",
"Width": "2",
"Make": "3"
}

我得到一个错误:FormatException: Input string was not in a correct format. AutoMapperMappingException: Error mapping types. Property: Length

是否需要配置某些内容才能让 AutoMapper 成功映射它?

最佳答案

你需要Custom Value Resolvers :

CreateMap<SourceThing, DestinationThing>()
.ForMember(dest => dest.Length,
opt => opt.MapFrom(src => string.IsNullOrWhiteSpace(src.Length)
? default(int)
: int.Parse(src.Length))

关于c# - AutoMapper - 将空字符串映射到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49577368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com