【发布时间】:2023-04-09 02:20:01
【问题描述】:
看到how to ignore a property type with Automapper后,我在一个测试项目中尝试过。事实证明,特定类型的属性被正确忽略,但在调用AssertConfigurationIsValid() 时抛出异常,指定找到未映射的成员。我可以理解这个异常的原因,因为应该忽略的类型的成员没有被映射,但我想知道是否应该在我故意删除映射的上下文中抛出这个异常。
对于给定的代码:
class Type1
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
}
class Type2
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
public TypeToIgnore Prop3 { get; set; }
}
class MappingProfile : Profile
{
public MappingProfile()
{
ShouldMapProperty = p => p.PropertyType != typeof(TypeToIgnore);
CreateMap<Type2, Type1>();
}
}
//...
var config = new MapperConfiguration(cfg => cfg.AddProfile(new MappingProfile()));
config.AssertConfigurationIsValid(); //this throws AutoMapperConfigurationException
Automapper在验证配置的有效性时忽略成员而不抛出异常不就是正确的行为吗,就像忽略属性本身的情况一样?
CreateMap<Type2, Type1>().ForMember(x => x.Prop3, y => y.Ignore());
【问题讨论】:
-
它只会验证@ZorgoZ 指出的目的地尝试反转您的 CreateMap 类型,然后调用 ReverseMap:
CreateMap<Type1, Type2>().ReverseMap();仍应允许从 Type2 映射到 Type1。 -
@mxmissile 感谢您的回复,从 ZorgoZ 给出的答案中可以看出,我认为 Automapper API 的工作方式与其不同。
标签: c# automapper