How to implement IEquatable when mutable fields are part of the equality - Problem with GetHashCode

前端 未结 2 549
暗喜
暗喜 2021-01-24 05:21

I am using Entity Framework in my application.

I implemented with the partial class of an entity the IEquatable interface:

Partial          


        
2条回答
  •  孤城傲影
    2021-01-24 05:43

    You've used a mutable field (AddressId) as part of the hash - that is unfortunately doomed. By which I mean: when you add it, the AddressId is 0? -1? it doesn't matter what exactly, but it isn't the final id - and it is stored with this key / hash. When you save it, the actual id (the IDENTITY column from the database) is updated into the object.

    Quite simply, you cannot reliably hash against this value if it can change when it is part of a dictionary. One possible workaround would be to consider the unit-of-work, i.e. an insert is a unit-of-work. Meaning: if the data etc only lives as long as this, then it is a non-issue as you will never attempt to access the data after saving it. Subsequently (in a different context) loading the data should be fine too, as the id doesn't then change during the lifetime.

    Alternatively: drop this hash/equality.

提交回复
热议问题