What would be considered the best practice in duplicating [cloning] a LINQ to SQL entity resulting in a new record in the database?
The context is that I wish to make a duplicate function for records in a grid of an admin. website and after trying a few things and the obvious, read data, alter ID=0, change name, submitChanges()
, and hitting an exception, lol. I thought I might stop and ask an expert.
I wish to start with first reading the record, altering the name by prefixing with "Copy Of " and then saving as a new record.
If you load entity from DataContext with set ObjectTrackingEnabled to false then you can insert this entity as new in another DataContext
DataContext db1 = new DataContext();
DataContext db2 = new DataContext();
db2.ObjectTrackingEnabled = false;
MyEntity entToClone = db2.Single(e => e.Id == id);
// ... change some data if it is needed
db1.MyEntities.InsertOnSubmit(entToClone);
db1.SubmitChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With