gpt4 book ai didi

c# - Automapper AssertConfigurationIsValid 不检查 ReverseMap

转载 作者:行者123 更新时间:2023-12-04 17:41:31 24 4
gpt4 key购买 nike

当我创建映射 1->2 然后反转它时,我希望得到与映射 2->1 和反转相同的结果。正确的?但是AssertConfigurationIsValid一种情况成功,另一种情况失败。

例如,

public class Basic1
{
public string Name;
public int Age;
}

public class Basic2
{
public string Name;
}


public void TestAutoMapperBasic()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Basic1, Basic2>()
.ForMember(dest => dest.Name, c => c.MapFrom(src => src.Name))
.ReverseMap();
});
Mapper.AssertConfigurationIsValid();
}

这会成功吗?!!!但如果我把它倒过来,就是CreateMap<Basic2, Basic1>那么它将失败。

我要AssertConfigurationIsValid实际检查两个方向,而不仅仅是一个方向。我该怎么做?

最佳答案

这是预期的行为,因为 described here由开发者提供。

Ah, this is the expected behavior. ReverseMap is different, itassumes you're literally flattening and un-flattening. Forun-flattening, you'd want to assert that the source side is allmapped, not the destination. Reverse map doesn't assume you want toassert anything, since you've already validated the Source ->Destination mapping.

In short, ReverseMap is now "special" and not merely a short cut fortwo CreateMap calls.

如果你想指定反向映射也应该验证,你可以这样明确指定:

config.ReverseMap().ValidateMemberList(MemberList.Destination)

您还可以创建一个扩展方法作为此的快捷方式:

public static IMappingExpression<TDestination, TSource> ReverseMapWithValidation<TSource, TDestination>(this IMappingExpression<TSource, TDestination> mapping)
=> mapping.ReverseMap().ValidateMemberList(MemberList.Destination);

关于c# - Automapper AssertConfigurationIsValid 不检查 ReverseMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54316626/

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