我在我的应用程序中使用实体框架。
我用实体的部分类实现了IEquatable<T>
接口:
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
现在在我的代码中,我以这种方式使用它:
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
注意(我在调试器可视化器中检查)EntityCollection 类将其实体存储在 HashSet 中,因此它与 GetHashCode 函数有关,我希望它依赖于 ID,因此实体通过它们的 ID 进行比较。
问题是当我点击保存时,ID 从 0 变为它的 db 值。所以问题是我怎样才能有一个平等的对象,被正确地散列。
请帮助我找出 GetHashCode 函数中的问题(按 ID)以及我可以更改哪些内容以使其正常工作。
非常感谢。