Tuesday, 14 December 2010

Beware of Automapper modifying protected fields

I've just spent a good couple of hours trying to debug what appeared to be a corrupt session in NHibernate.  The unit tests would work, isolating the NHibernate code causing the problem worked, but within the application when calling Session.Save() the code always complained about a corrupt session.  Finally after much investigation and head scratching the problem was traced to an earlier call to AutoMapper.   This code was mapping an ID in the source to a UserID in the target - which had been correctly defined in the mapping file and worked without any problems.  What I had missed however was that AutoMapper was mapping the source ID to the "protected" target ID which NHibernate was using as it's entity key.  When using the entity directly you can't change the ID as it is protected (so it can safely stay under the control of NHibernates).  However automapper obviously uses reflection so passes the "protected" status of the property and in doing so was breaking referential intergity.  In the end all that was needed was to update the mapping to ignore / use destination value for the mapping of ID on destination.  Problem Solved.

No comments:

Post a Comment