0

I have a PhoneRecord that is passed to an EditWindow so that a user is able to edit the record. On each PhoneRecord there is a type of CostCode. On the EditWindow I clone a record to break the reference to the SelectedRecord so that in case the user clicks on cancel I can pass back an unmodified version of the PhoneRecord. Here is how I clone:

public ModifyPhoneRecordViewModel(PhoneRecord passedRecord)
{
    SelectedRecord = passedRecord;
    _tempRecord = passedRecord.Clone() as PhoneRecord;
}

The PhoneRecord is a partial class generated by EF so here is how I implement ICloneable

partial class PhoneRecord : ICloneable
{
    public object Clone()
    {
        return (PhoneRecord)MemberwiseClone();
    }
}

When the user clicks on cancel I pass back the _tempRecord and do some processing with it to revert to it's original state in the DataGrid/TextBoxes:

private void ProcessCancelCommand(PhoneRecord passedRecord)
{
    DataGridRecords[DataGridRecords.IndexOf(DataGridRecords.FirstOrDefault(c => c.Id == passedRecord.Id))] = passedRecord;

    SelectedRecord = passedRecord;

    Application.Current.MainWindow.Activate();
}

However, this throws an error and the CostCode is wiped from the TextBox:

"The entity wrapper stored in the proxy does not reference the same proxy"

Is there a way in which I can prevent this so I can pass back a PhoneRecord with a valid CostCode on it?

CBreeze
  • 2,925
  • 4
  • 38
  • 93
  • You are trying to copy DB entity, that uses lazy loading and therefore it's just a proxy. That's why code throwing an error. https://stackoverflow.com/questions/25770369/get-underlying-entity-object-from-entity-framework-proxy Provides an unproxy method – Danil Eroshenko Sep 07 '17 at 07:45
  • @DanilEroshenko So do I need to use something like `var x = ObjectContext.GetObjectType(_tempRecord.GetType());` ? How does that return a useable `PhoneModel` to me? – CBreeze Sep 07 '17 at 07:58
  • I was pointing at UnProxy method actually. Also I think that Clone using serialization should also work https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-of-an-object-in-net-c-specifically – Danil Eroshenko Sep 07 '17 at 10:24

1 Answers1

0

You could try not to use the MemberwiseClone() method to clone your entity:

EntityFramework - Entity proxy error

...but simply create a new entity class yourself:

partial class PhoneRecord : ICloneable
{
    public object Clone()
    {
        return new PhoneRecord()
        {
            CostCode = this.CostCode,
            //+ all other properties...
        }
    }
}

You don't want to clone the proxy class.

mm8
  • 163,881
  • 10
  • 57
  • 88