Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement IEquatable<T> when mutable fields are part of the equality - Problem with GetHashCode
    text
    copied!<p>I am using Entity Framework in my application.</p> <p>I implemented with the partial class of an entity the <code>IEquatable&lt;T&gt;</code> interface:</p> <pre><code>Partial Class Address : Implements IEquatable(Of Address) 'Other part generated Public Overloads Function Equals(ByVal other As Address) As Boolean _ Implements System.IEquatable(Of Address).Equals If ReferenceEquals(Me, other) Then Return True Return AddressId = other.AddressId End Function Public Overrides Function Equals(ByVal obj As Object) As Boolean If obj Is Nothing Then Return MyBase.Equals(obj) If TypeOf obj Is Address Then Return Equals(DirectCast(obj, Address)) Else Return False End Function Public Overrides Function GetHashCode() As Integer Return AddressId.GetHashCode End Function End Class </code></pre> <p>Now in my code I use it this way:</p> <pre><code>Sub Main() Using e As New CompleteKitchenEntities Dim job = e.Job.FirstOrDefault Dim address As New Address() job.Addresses.Add(address) Dim contains1 = job.Addresses.Contains(address) 'True e.SaveChanges() Dim contains2 = job.Addresses.Contains(address) 'False 'The problem is that I can't remove it: Dim removed = job.Addresses.Remoeve(address) 'False End Using End Sub </code></pre> <p>Note (I checked in the debugger visualizer) that the EntityCollection class stores its entities in HashSet so it has to do with the GetHashCode function, I want it to depend on the ID so entities are compared by their IDs.</p> <p>The problem is that when I hit save, the ID changes from 0 to its db value. So the question is how can I have an equatable object, being properly hashed.</p> <p>Please help me find what's wrong in the GetHashCode function (by ID) and what can I change to make it work.</p> <p>Thanks a lot.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload