简体   繁体   English

为什么我不能在EF4中的多对多实体上覆盖GetHashCode?

[英]Why can't I override GetHashCode on a many-to-many entity in EF4?

I have a many-to-many relationship in my Entity Framework 4 model (which works with a MS SQL Server Express): Patient-PatientDevice-Device. 我的Entity Framework 4模型(与MS SQL Server Express一起使用)中有多对多的关系:Patient-PatientDevice-Device。 I'm using Poco, so my PatientDevice-class looks like this: 我正在使用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;
    //}
}

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. 但是,如果我在PatientDevice-class中取消注释GetHashCode,患者仍然会先添加PatientDevice。

What is wrong in overriding GetHashCode and returning the Id? 覆盖GetHashCode并返回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. 另一个问题是GetHashCode()的结果在某些情况下在对象的生命周期内可能不会改变,并且这些可能适用于实体框架。 This together with the Id begin 0 when it's created also poses problems. 这与Id一起创建0时也会产生问题。

An alternative of GetHashCode() is: 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;
}

Taken from http://nhforge.org/blogs/nhibernate/archive/2008/09/06/identity-field-equality-and-hash-code.aspx . 取自http://nhforge.org/blogs/nhibernate/archive/2008/09/06/identity-field-equality-and-hash-code.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM