LINQ – Copy an Entity in Different Contexts

Error:

“An entity object cannot be referenced by multiple instances of IEntityChangeTracker.”

Solution:

“ApplyCurrentValues” method. (For Framework 3.5 “ApplyPropertyChanges”)

This solution is might be useful if you want to copy the scalar values of an entity to another entity that is belong to a different context.

For example I have a method that takes an invoice entity and updates it.

public bool UpdateInvoice(InvoiceEntity invoice)

{

int res = 0;

try

{

using (MyEntities dataModel = new MyEntities ())

{

var originalRecord = (from p in dataModel.InvoiceEntity

where p.InvoiceId == invoice.InvoiceId

select p).FirstOrDefault();

dataModel.ApplyCurrentValues(originalRecord.EntityKey.EntitySetName, invoice);

res = _dataModel.SaveChanges();

}

}

catch (Exception ex)

{

//Logging

throw ex;

}

return res > 0;

}

If you wish, Instead of this method you can create a new instance of the invoice and asign the values using the invoice in the method parameters. However, you have to update that code whenever the invoice table updated.

Leave a Reply

Your email address will not be published. Required fields are marked *