1

I have the following objects:

public class DomainStudent {
    public long Id { get; set; }
    public string AdvisorId { get; set; }
}

public class ApiStudent {
    public long Id { get; set; }
    public long AdvisorName { get; set; }
}

When I run the following mapping:

ApiStudent api = new ApiStudent();
api.Id = 123;
api.AdvisorName = "Homer Simpson";

DomainStudent existing = service.load(api.Id); // 123
// at this point existing.AdvisorId = 555

existing = Mapper.Map<ApiStudent, DomainStudent>(api);
// at this point existing.AdvisorId = null

How can I configure AutoMapper such that when the property AdvisorId is missing from the source object, so that it does not get overwritten to null?

4
  • 1
    Could you please correct the code first? AdvisorName is declared as long but "Homer Simpson" is assigned to it. Commented Apr 10, 2013 at 16:09
  • Does this question: Merge two objects to produce third using AutoMapper help you at all? Commented Apr 10, 2013 at 16:15
  • try this: stackoverflow.com/questions/13194072/… Commented Apr 10, 2013 at 16:35
  • This isn't quite what I want. ... what I want is to NOT overwrite a field to NULL if it didn't have a matching field on the source object. Commented Apr 10, 2013 at 18:13

1 Answer 1

3

You must change the Map() call to:

Mapper.Map(api, existing);

and then configure the mapping to:

 Mapper.CreateMap<ApiStudent, DomainStudent>()
            .ForMember(dest => dest.AdvisorId, opt => opt.Ignore());
Sign up to request clarification or add additional context in comments.

2 Comments

The second code snippet should be Mapper.CreateMap<ApiStudent, DomainStudent>()... instead of CreateMap<ApiStudent, DomainStudent>()... since CreateMap is a static method.
@RyanGates Fixed. I copied from my AutoMapper Profile classes and forgot to change it.

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.