c# - Why can't I override GetHashCode on a many-to-many entity in EF4? -


i have many-to-many relationship in entity framework 4 model (which works ms sql server express): patient-patientdevice-device. i'm using poco, patientdevice-class looks 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;     //} } 

all works when 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 uncomment gethashcode in patientdevice-class, patient still has patientdevice added earlier.

what wrong in overriding gethashcode , returning id?

the reason may class type not part of hash code, , entity framework has difficulty distinguishing between different types.

try following:

public override int gethashcode() {     return id ^ gettype().gethashcode(); } 

another problem result of gethashcode() may not change during lifetime of object under circumstances, , these may apply entity framework. id begin 0 when it's created 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 when above not work.             // _hashcode.value = id ^ gettype().gethashcode();     }      return _hascode.value; } 

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


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -