我的 Entity Framework 4 模型(与 MS SQL Server Express 一起使用)中存在多对多关系:Patient-PatientDevice-Device。我正在使用 Poco,所以我的 PatientDevice 类如下所示:
public class PatientDevice
{
protected virtual Int32 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;
//}
}
当我这样做时一切正常:
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);
但是,如果我在 PatientDevice 类中取消注释 GetHashCode,患者仍然拥有之前添加的 PatientDevice。
覆盖 GetHashCode 并返回 Id 有什么问题?
最佳答案
原因很可能是类类型不是哈希码的一部分, Entity Framework 很难区分不同的类型。
尝试以下操作:
public override int GetHashCode()
{
return Id ^ GetType().GetHashCode();
}
另一个问题是,在某些情况下,GetHashCode()
的结果在对象的生命周期内可能不会改变,这些可能适用于 Entity Framework 。这与 Id
在创建时以 0 开头也会带来问题。
GetHashCode()
的替代方法是:
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;
}
取自http://nhforge.org/blogs/nhibernate/archive/2008/09/06/identity-field-equality-and-hash-code.aspx .
关于c# - 为什么我不能在 EF4 中的多对多实体上重写 GetHashCode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4185537/