Why can't I override GetHashCode on a many-to-many basis in EF4?

I have a many-to-many relationship in my Entity Framework 4 model (which works with MS SQL Server Express): Patient-PatientDevice-Device. I use Poco, so my PatientDevice class looks like this:

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;
    //}
}

Everything 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 the PatientDevice class, the patient still has the PatientDevice added earlier.

What is wrong with overriding GetHashCode and returning an identifier?

+3
source share
1 answer

, - .

:

public override int GetHashCode()
{
    return Id ^ GetType().GetHashCode();
}

, GetHashCode() , . Id begin 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.

+1

Source: https://habr.com/ru/post/1774970/


All Articles