Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper maps correctly on first call but skips properties on second call

I have the following classes defined:

public class ImageIndexModel {
   public string Description {get; set;}
   public string InstrumentNumber {get; set;}
}

public class ImageEditModel : ImageIndexModel {
    public int TotalCount = 0;
}

public class Clerk {  //This is actually a class defined by LinqToSql
    public string Description {get; set;}
    public string InstrumentNo {get; set;}
}

Now, in my global.asax, I've defined the following Mapping in Application_Start().

Mapper.CreateMap<ImageIndexModel, Clerk>()
   .ForMember(dest => dest.InstrumentNo,
              opt => opt.MapFrom(src => src.InstrumentNumber));

Lastly, in one of my controllers, I have the following code:

var _existing = new Clerk();
var _default = new ImageEditModel() {
                 InstrumentNumber = "12345678", Description = "Test"
               };
Mapper.Map(_default, _existing);

The first time I call the Action on my controller and this mapping is run, everything works fine and the InstrumentNumber is correctly mapped to the InstrumentNo of the Clerk object. However, the second time the Action gets called, InstrumentNo does not get mapped. InstrumentNumber definitely has a value but InstrumentNo remains null.

Any ideas what might be happening here?

like image 993
RHarris Avatar asked Nov 13 '22 13:11

RHarris


1 Answers

I once had the opposite problem, where too many mappings were happening. It was resolved by calling mapper.reset() as described here for potentially other reasons. Perhaps something else in your application is resetting your mapper out from underneath you such that it is no longer resolving mappings which you believe it should (and does for a short while)? The key from the other question is that Automapper is singleton, and so another portion of your code can load or late-bind and foul it up without you knowing.

like image 109
Greg Avatar answered Nov 15 '22 05:11

Greg