Lazy-loaded NHibernate properties in Equals and GetHashCode

后端 未结 3 1449
夕颜
夕颜 2021-01-03 03:49

How can the following problem be dealt with?

We\'re using lazy loaded NHibernate properties and whenever we\'re calling Equals() or GetHashCode()<

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 04:42

    I use the following rules:

    1. If entity has a POID property (remember that there is not need of property or any member just omit the name="XX", not sure if activerecord or the mapping strategy you are using supoprt this)

      • Not transient: If instance has ID != default(idType) then it is equals to another entity if both have the same id.
      • Transient: If instance has ID == default(idType) then it is equals to another entity if both are the same Reference. ReferenceEquals(this, other).
    2. If entity doesn't have a POID property, for sure you will need a natural-id. Use natural id for equality and GetHashCode.

    3. If you have a natural-id with many-to-one, instead of doing FooProperty.Equals(other.FooProperty), use FooProperty.Id.Equals(other.FooProperty.Id). Accessing the ID doesn't trigger the initialization of the lazy reference.

    Last but not least, using composite-id is discourage, and composite id with key-many-to-one is very discourage.

提交回复
热议问题