I have a requirement to clone a Linq to SQL object. In Review:
Customer origCustomer = db.Customers.SingleOrDefault(c => c.CustomerId == 5); Customer newCustomer = CloneUtils.Clone(origCustomer); newCustomer.CustomerId = 0;
where CloneUtils.Clone () is a simple general method that uses reflection to copy a copy of the data from the original object to the new object.
The problem is that when I try to add a new object back to the database, I get the following error:
An attempt was made to insert or add an object that is not new, it may have been loaded from another DataContext. This is not supported.
I cannot find a simple / general way to detach a cloned object from a data context. Or maybe I can set the cloning method to “skip” context-related fields?
Can someone point me in the right direction?
Thanks.
For completeness, here is the way I ended up with the following Marcus advice:
public static T ShallowClone<T>(T srcObject) where T : class, new() {
Neilski
source share