Does this solve Nhibernate identity problem and GetHashCode issues?

后端 未结 3 2107
逝去的感伤
逝去的感伤 2021-01-22 03:22

The solution I propose involves quite a bit of code, but you can just copy it all and past it in a VS test solution assuming you have SqLite installed, and you should be able to

3条回答
  •  星月不相逢
    2021-01-22 04:13

    I think the basic misconception here is that you implement Equals and GetHashCode based on business data. I don't know why you prefer that, I can't see any advantage in it. Except - of course - when dealing with a value object which doesn't have an Id.

    There is a great post on nhforge.org about Identity Field, Equality and Hash Code

    Edit: This part of your code will cause problems:

        public static class IdentityChanger
        {
            public static void ChangeIdentity(Action changeIdentity, T newIdentity, ISession session)
            {
                changeIdentity.Invoke(newIdentity);
                session.Flush();
                session.Clear();
            }
        }
    
    1. Flushing is expensive
    2. Clearing the session makes NH loading the same entities again.
      1. It may produce much too many db queries because the entities aren't found in the session anymore.
      2. It may produce confusion when an entity that had been read from the db is linked to another and NH complains that it is transient
      3. It may produce memory leaks, for instance when it happens in a loop

    You should implement Equals and GetHashCode based on immutable data. Changing the hash is not possible in a reasonable way.

提交回复
热议问题