Linq Cloning for Sql Entity - Removing Data Context

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; // Clear key db.Customers.InsertOnSubmit(newCustomer); db.SubmitChanges(); // throws an error 

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() { // Get the object type Type objectType = typeof(T); // Get the public properties of the object PropertyInfo[] propInfo = srcObject.GetType() .GetProperties( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public ); // Create a new object T newObject = new T(); // Loop through all the properties and copy the information // from the source object to the new instance foreach (PropertyInfo p in propInfo) { Type t = p.PropertyType; if ((t.IsValueType || t == typeof(string)) && (p.CanRead) && (p.CanWrite)) { p.SetValue(newObject, p.GetValue(srcObject, null), null); } } // Return the cloned object. return newObject; } 
+7
source share
1 answer

Only clone public properties

 var PropertyBindings = BindingFlags.Public | BindingFlags.Instance; 

These are value types or string

 var PropType = p.PropertyType.IsValueType || p.PropertyType == typeof(string); 

And available available

  var IsAccessible = p.CanRead && p.CanWrite; 
+6
source

All Articles