4

I use Automapper to map object source to object destination. Is there any way to map, only properties that has non-default value, from source object to destination object?

0

1 Answer 1

5

The key point is to check the source property's type and map only if these conditions are satisfied (!= null for a reference type, != default for a value type):

Mapper.CreateMap<Src, Dest>()
    .ForAllMembers(opt => opt.Condition(
        context => (context.SourceType.IsClass && !context.IsSourceValueNull)
            || ( context.SourceType.IsValueType
                 && !context.SourceValue.Equals(Activator.CreateInstance(context.SourceType))
                )));

The full solution is:

public class Src
{
    public int V1 { get; set; }
    public int V2 { get; set; }
    public CustomClass R1 { get; set; }
    public CustomClass R2 { get; set; }
}

public class Dest
{
    public int V1 { get; set; }
    public int V2 { get; set; }
    public CustomClass R1 { get; set; }
    public CustomClass R2 { get; set; }
}

public class CustomClass
{
    public CustomClass(string id) { Id = id; }

    public string Id { get; set; }
}

[Test]
public void IgnorePropertiesWithDefaultValue_Test()
{
    Mapper.CreateMap<Src, Dest>()
        .ForAllMembers(opt => opt.Condition(
            context => (context.SourceType.IsClass && !context.IsSourceValueNull)
                || ( context.SourceType.IsValueType
                     && !context.SourceValue.Equals(Activator.CreateInstance(context.SourceType))
                    )));

    var src = new Src();
    src.V2 = 42;
    src.R2 = new CustomClass("src obj");

    var dest = new Dest();
    dest.V1 = 1;
    dest.R1 = new CustomClass("dest obj");

    Mapper.Map(src, dest);

    //not mapped because of null/default value in src
    Assert.AreEqual(1, dest.V1);
    Assert.AreEqual("dest obj", dest.R1.Id);

    //mapped 
    Assert.AreEqual(42, dest.V2);
    Assert.AreEqual("src obj", dest.R2.Id);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.