I have a many-to-many relationship in my Entity Framework 4 model (which works with a MS SQL Server Express): Patient-PatientDevice-Device. I'm using Poco, so my PatientDevice-class looks like this:
public class PatientDevice
{
protected virtual I开发者_高级运维nt32 Id { get; set; }
protected virtual Int32 PatientId { get; set; }
public virtual Int32 PhysicalDeviceId { get; set; }
public virtual Patient Patient { get; set; }
public virtual Device Device { get; set; }
//public override int GetHashCode()
//{
// return Id;
//}
}
All works well when I do this:
var context = new Entities();
var patient = new Patient();
var device = new Device();
context.PatientDevices.AddObject(new PatientDevice { Patient = patient, Device = device });
context.SaveChanges();
Assert.AreEqual(1, patient.PatientDevices.Count);
foreach (var pd in context.PatientDevices.ToList())
{
context.PatientDevices.DeleteObject(pd);
}
context.SaveChanges();
Assert.AreEqual(0, patient.PatientDevices.Count);
But if I uncomment GetHashCode in PatientDevice-class, the patient still has the PatientDevice added earlier.
What is wrong in overriding GetHashCode and returning the Id?
The reason may very well be that the class type is not part of the hash code, and that the entity framework has difficulty distinguishing between the different types.
Try the following:
public override int GetHashCode()
{
return Id ^ GetType().GetHashCode();
}
Another problem is that the result of GetHashCode()
may not change during the lifetime of an object under certain circumstances, and these may apply for the entity framework. This together with the Id
begin 0 when it's created also poses problems.
An alternative of GetHashCode()
is:
private int? _hashCode;
public override int GetHashCode()
{
if (!_hashCode.HasValue)
{
if (Id == 0)
_hashCode.Value = base.GetHashCode();
else
_hashCode.Value = Id;
// Or this when the above does not work.
// _hashCode.Value = Id ^ GetType().GetHashCode();
}
return _hasCode.Value;
}
Taken from http://nhforge.org/blogs/nhibernate/archive/2008/09/06/identity-field-equality-and-hash-code.aspx.
精彩评论