C# 为什么可以';我在EF4中的多对多实体上重写GetHashCode吗?
我的Entity Framework 4模型(与MS SQL Server Express配合使用)中存在多对多关系:Patient PatientDevice。我正在使用Poco,因此我的PatientDevice类如下所示:C# 为什么可以';我在EF4中的多对多实体上重写GetHashCode吗?,c#,entity-framework,many-to-many,gethashcode,C#,Entity Framework,Many To Many,Gethashcode,我的Entity Framework 4模型(与MS SQL Server Express配合使用)中存在多对多关系:Patient PatientDevice。我正在使用Poco,因此我的PatientDevice类如下所示: public class PatientDevice { protected virtual Int32 Id { get; set; } protected virtual Int32 PatientId { get; set; } publi
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有什么错?原因很可能是类类型不是哈希代码的一部分,实体框架很难区分不同的类型 请尝试以下操作:
public override int GetHashCode()
{
return Id ^ GetType().GetHashCode();
}
另一个问题是,在某些情况下,GetHashCode()
的结果在对象的生命周期内可能不会更改,这些可能适用于实体框架。这与创建时的Id
begin0一起也会带来问题
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;
}
摘自。为添加和删除操作创建新的
上下文时会发生什么情况?使用新上下文删除会起作用(我忘了提到:PatientDevice在数据库上也只使用一个上下文删除)。patient.PatientDevices的Id
的值是多少[0]
在您使用GetHashCode()
实现的断言
(在每一端)时?550-该数字是从SQL server提供给我的。您是否覆盖GetHashCode
,但不覆盖等于
GetHashCode
与对象标识无关。不,抱歉。PatientDevice仍然存在。还记得一篇老帖子,其中讨论了瞬态实体(Id==0
),以及在实体的生存期内,GetHashCode()
的结果不应更改的事实。试试看。