Passing ICloneable Class throws Proxy error

664 Views Asked by At

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?

1

There are 1 best solutions below

1
mm8 On BEST ANSWER

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.