0

I have the following two classes:

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

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

When I run the following mapping:

Mapper.CreateMap<ApiStudent, DomainStudent>();

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

var domain = new DomainStudent();
domain.Id = 123;
domain.AdvisorName = "Marge Simpson";
domain.DegreeId = 5; // i want this to get written to null

Mapper.Map(api, domain);
// at this point domain.DegreeId = 5 instead of null

I would have thought this worked by default. Am I missing something?

1
  • 1
    This works for me, see this example Commented Sep 13, 2014 at 19:08

1 Answer 1

4

By default automapper will ignore null source values.

You can change this with the following:

Mapper.Initialize( Conf =>
  {
    Conf.ForSourceType<ApiStudent>().AllowNullDestinationValues = true;
  } );

Otherwise you can try:

Mapper.CreateMap<long?, long?>()
    .ConvertUsing(v => v);

Pretty ugly hack to have to do something like this but it might work.

edit: Just for clarity I wanted to note the final solution to the question was upgrading to AutoMapper version 3.2.1

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer... I actually tried that already and it does not work believe it or not.
and is definitely in a position where it's getting hit? Sorry, don't really have any other ideas :(
Yeah, I'm doing a post check using reflection on every property to make sure they all match up. That second suggestion does work, but that seems like it my affect the rest of my application in a way I might not want. Is there a reason this just doesn't work right out of the box? It seems like all I'm asking for here is default behavior.
@AdamLevitt I just made a new test project with the latest automapper, and the behavior you're looking for is working by default. Are you on the latest version of AutoMapper?
Tom, what version are you using on your end?
|

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.