首页 新闻 会员 周边

automapper我已经设置了忽略空的参数,为啥还报错

0
悬赏园豆:5 [已解决问题] 解决于 2024-01-31 08:52

automapper我已经设置了忽略空的参数,为啥还报错,我这个id是string转int64

/// <summary>
/// 对象映射
/// </summary>
/// <typeparam name="TSource">源对象类型</typeparam>
/// <typeparam name="TDestination">目标对象类型</typeparam>
/// <param name="source">源对象</param>
/// <param name="ignoreEmptyOrNull">是否忽悠null空值</param>
/// <returns></returns>
public static TDestination Map<TSource, TDestination>(TSource source)
{
Action<IMapperConfigurationExpression> configure = s => s.CreateMap<TSource, TDestination>()
.ForAllMembers(s => s.Condition((source, dest, sourceMember) =>
{
return sourceMember != null && !string.IsNullOrWhiteSpace(sourceMember.ToString());
}));
MapperConfiguration configuration = new MapperConfiguration(configure);
var mapper = configuration.CreateMapper();
var result = mapper.Map<TSource,TDestination>(source);
return result;

    }

Error mapping types.
Input string was not in a correct format.

Mapping types:
EditArticleDTO -> Article
XianDan.Model.DTO.Article.EditArticleDTO -> XianDan.Domain.Blog.Article

Type Map configuration:
EditArticleDTO -> Article
XianDan.Model.DTO.Article.EditArticleDTO -> XianDan.Domain.Blog.Article

Destination Member:
Id

灬丶的主页 灬丶 | 初学一级 | 园豆:4
提问于:2023-12-14 21:08

建议改进一下排版,支持markdown代码高亮语法

dudu 4个月前
< >
分享
最佳答案
0

通过反射将空转为null

灬丶 | 初学一级 |园豆:4 | 2024-01-02 14:33
其他回答(2)
0

Input string was not in a correct format. 不能说明是空字符串

收获园豆:3
dudu | 园豆:30943 (高人七级) | 2023-12-14 21:48
0

看起来你的问题可能与string到int64的转换有关。根据错误消息 "Input string was not in a correct format.",可能是因为在映射过程中,尝试将一个无效格式的字符串赋给目标类型的Id属性,而这个属性的类型是int64。

在AutoMapper的配置中,可能需要在源对象和目标对象之间进行更精确的映射。你可以使用ForMember方法来配置具体的成员映射规则。在这个情况下,你可以尝试添加对Id属性的映射规则,以确保正确的转换。

例如,你可以在配置中添加以下内容:

csharp
Copy code
Action<IMapperConfigurationExpression> configure = s => s.CreateMap<TSource, TDestination>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => Convert.ToInt64(src.Id)))
.ForAllMembers(s => s.Condition((source, dest, sourceMember) =>
{
return sourceMember != null && !string.IsNullOrWhiteSpace(sourceMember.ToString());
}));
这个配置会告诉AutoMapper在映射过程中将源对象的Id属性转换为int64,并将结果赋给目标对象的Id属性。这样,你就可以避免 "Input string was not in a correct format." 的错误。请确保在进行类型转换时,源对象的Id属性确实包含有效的int64字符串。

如果你的Id属性的类型在源对象和目标对象中不同,还需要确保进行适当的类型转换。

收获园豆:2
Technologyforgood | 园豆:5686 (大侠五级) | 2023-12-14 22:13

我的源字符串可能是空的

支持(0) 反对(0) 灬丶 | 园豆:4 (初学一级) | 2023-12-15 08:37
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册