Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate LINQ to SQL entity / record?

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.

like image 649
GONeale Avatar asked Mar 12 '09 06:03

GONeale


1 Answers

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();
like image 103
Peter K. Avatar answered Sep 22 '22 05:09

Peter K.