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.
I was stuck with the same problem and Kristofer's code worked perfectly, many thanks!
In case someone is interested, I slightly modified his code so that instead of accepting the target entity as a parameter, it creates a new object and returns it. Also I have made the
sourceEntity
parameter to be generic:Then I can do the following:
Here is he same solution as Peter K., for the Linq-to-Sql Entiry Clone in VB.Net.
If you load entity from DataContext with set ObjectTrackingEnabled to false then you can insert this entity as new in another DataContext
Create a new instance and then use the linq mapping classes together with reflection to copy member values.
E.g.
...or you can clone it using the DataContractSerializer:
In Entity framework 6 you can do this