KeyNotFoundException from NHibernate’s Session.Evict
We started getting KeyNotFoundException when we evict an entity from session. The error is not consistent, some time it work and some time it wont. Searched a lot for the cause of this exception but not got any proper solution.
As per the stack trace, the error is because it couldn’t find the key in a collection. In a collection an entities identity is based on the hash code. In this case the entity has composite key. In the GetHashCode function, we append the values of composite properties and get the hash code of the resultant string. When I start checking in more details I saw some properties we used in getting hash code is not exist as part composite key in the mapping file (some keys were removed from the composite mapping but not updated GetHasCode()). I need to do some more analysis to find why those extra fields screwing up the GetHashCode function. I will update the post later if I get the answer.
To avoid these kind of issues make sure to use only composite properties in the Equal and GetHashCode function and avoid using properties that are not part of composite.