在我看到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());
AutoMapper从源映射到目标。据我所知,默认情况下,源中存在但目标类型中缺少的字段将被忽略。您必须显式处理的是源中缺少的字段,但存在于目标类型中。在你的情况下,TypeToIgnore
在源头。因此,通过忽略该类型,您在目的地中没有Prop3
的源对应物。
举个例子,这不会抛出异常:
ShouldMapProperty = p => p.PropertyType != typeof(TypeToIgnore);
CreateMap<Type1, Type2>();
这也不会:
public class TypeToIgnore { }
void Main()
{
var config = new MapperConfiguration(cfg => cfg.AddProfile(new MappingProfile()));
config.AssertConfigurationIsValid(); // won't throw
}
class Type1
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
public bool Prop3 { get; set; } // <- because bool is ignored, you could simply delete this row
}
class Type2
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
public TypeToIgnore Prop3 { get; set; }
public long Prop4 { get; set; }
public double Prop5 { get; set; }
}
class MappingProfile : Profile
{
public MappingProfile()
{
ShouldMapProperty = p => p.PropertyType != typeof(bool);
CreateMap<Type2, Type1>();
}
}