也许这是设计的,但我们最初并不期望automapper能够捕获并忽略映射中的所有NullReferenceExceptions。我们主要使用MapFrom并创建有时复杂的表达式。如果有任何异常,甚至是NullReferenceException,我们希望这些映射失败,但我们不能让AutoMapper这样做。有没有办法让automapper不忽略所有这些异常,而不必为每个案例编写自定义值解析器?这对我们来说意味着很多额外的代码,事实上,如果不首先使用automapper,它可能会减少代码。
这些是我们期望全部通过的测试:
[TestFixture]
public class Tests
{
[SetUp]
public void Setup() { Mapper.Reset(); }
[Test]
public void ShouldThrowMappingExceptionUsingMapFromExpression()
{
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.DestinationMember, o => o.MapFrom(s => s.SourceMember.SourceProperty))
;
Assert.Throws<AutoMapperMappingException>(() => Mapper.Map<Source, Destination>(new Source()));
}
[Test]
public void ShouldThrowMappingExceptionUsingResolveUsingExpression()
{
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.DestinationMember, o => o.ResolveUsing(s => s.SourceMember.SourceProperty))
;
Assert.Throws<AutoMapperMappingException>(() => Mapper.Map<Source, Destination>(new Source()));
}
[Test]
public void ShouldThrowMappingExceptionUsingResolverInstance()
{
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.DestinationMember, o => o.ResolveUsing(new TestValueResolver()).FromMember(s => s.SourceMember))
;
Assert.Throws<AutoMapperMappingException>(() => Mapper.Map<Source, Destination>(new Source()));
}
[Test]
public void ShouldThrowMappingExceptionUsingResolverType()
{
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.DestinationMember, o => o.ResolveUsing<TestValueResolver>().FromMember(s => s.SourceMember))
;
Assert.Throws<AutoMapperMappingException>(() => Mapper.Map<Source, Destination>(new Source()));
}
}
public class Destination
{
public string DestinationMember { get; set; }
}
public class Source
{
public SourceChild SourceMember { get; set; }
}
public class SourceChild
{
public string SourceProperty { get; set; }
}
public class TestValueResolver : ValueResolver<SourceChild, string>
{
protected override string ResolveCore(SourceChild source)
{
return source.SourceProperty;
}
}