Skip to content

Commit

Permalink
Added ability for custom resolver to programatically determine if the…
Browse files Browse the repository at this point in the history
… mapping should be ignored (and thus use destination value).

closes AutoMapper#21
  • Loading branch information
andreialecu authored and jbogard committed Jun 24, 2011
1 parent b22b971 commit 0c8ba33
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 2 deletions.
2 changes: 2 additions & 0 deletions src/AutoMapper/Mappers/TypeMapObjectMapperRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ private void MapPropertyValue(ResolutionContext context, IMappingEngineRunner ma
throw new AutoMapperMappingException(errorContext, ex);
}

if (result.ShouldIgnore) return;

if (propertyMap.UseDestinationValue)
{
destinationValue = propertyMap.DestinationProperty.GetValue(mappedObject);
Expand Down
10 changes: 8 additions & 2 deletions src/AutoMapper/ResolutionResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,20 @@ private ResolutionResult(object value, ResolutionContext context)
public Type Type { get { return _type; } }
public Type MemberType { get { return _memberType; } }
public ResolutionContext Context { get { return _context; } }

private Type ResolveType(object value, Type memberType)

public bool ShouldIgnore { get; set; }

private Type ResolveType(object value, Type memberType)
{
if (value == null)
return memberType;

return value.GetType();
}
public ResolutionResult Ignore()
{
return new ResolutionResult(Context) { ShouldIgnore = true };
}

public ResolutionResult New(object value)
{
Expand Down
42 changes: 42 additions & 0 deletions src/UnitTests/CustomMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,48 @@ public void Should_use_the_specified_constructor()
}
}


public class When_custom_resolver_requests_property_to_be_ignored : AutoMapperSpecBase
{
private Destination _result = new Destination() { Value = 55 };

public class Source
{
public int Value { get; set; }
}

public class Destination
{
public int Value { get; set; }
}

public class CustomValueResolver : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
return source.Ignore();
}
}

protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.Value, opt => opt.ResolveUsing<CustomValueResolver>().FromMember(src => src.Value));
}

protected override void Because_of()
{
_result = Mapper.Map(new Source { Value = 5 }, _result);
}

[Test]
public void Should_not_overwrite_destination_value()
{
_result.Value.ShouldEqual(55);
}
}


public class When_specifying_member_and_member_resolver_using_string_property_names : AutoMapperSpecBase
{
private Destination _result;
Expand Down

0 comments on commit 0c8ba33

Please sign in to comment.