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 integrity. 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!!!
As part of his fantastic ‘What is .NET standard‘ presentation at DDD12, Adam Ralph provided an amazing amount of detail in such a short amount of time. One of the most valuable points, which is completely obvious when you think about it, is how you should work with .NET standard when creating libraries. NET standard now comes in a multitude of flavours: currently 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6 and 2.0. When starting out . . .
If you’re trying to access a class library (.NET Standard) from a traditional console application (in VS2017 those can be found under ‘Windows Classic Desktop’) you will run into problems; which can feel a little strange for something that was pretty simple in VS2015 and earlier. You can add a reference to the class library project (Resharper will even volunteer to add the dependency / namespace reference if you don’t already have it). But the . . .