Linq to sql 克隆Linq到Sql实体-分离数据上下文

Linq to sql 克隆Linq到Sql实体-分离数据上下文,linq-to-sql,clone,detach,Linq To Sql,Clone,Detach,我需要克隆Linq到SQL实体。概述: Customer origCustomer = db.Customers.SingleOrDefault(c => c.CustomerId == 5); Customer newCustomer = CloneUtils.Clone(origCustomer); newCustomer.CustomerId = 0; // Clear key db.Customers.InsertOnSubmit(newCustomer); db.SubmitC

我需要克隆Linq到SQL实体。概述:

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
其中CloneUtils.Clone()是一个简单的通用方法,它使用反射将数据从原始实体复制到新实体

我遇到的问题是,当我尝试将新实体添加回数据库时,会出现以下错误:

已尝试附加或添加非新实体,可能是从另一个DataContext加载的。这是不受支持的

我似乎找不到一种简单/通用的方法将克隆实体从数据上下文中分离出来。或者我可以调整我的克隆方法以“跳过”与上下文相关的字段

谁能给我指出正确的方向吗

谢谢

为了完整起见,以下是我最后按照马库斯的建议得出的方法:

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;
}
publicstatict ShallowClone(tsrcobject),其中T:class,new()
{
//获取对象类型
类型objectType=typeof(T);
//获取对象的公共属性
PropertyInfo[]propInfo=srcObject.GetType()
.GetProperties(
System.Reflection.BindingFlags.Instance|
System.Reflection.BindingFlags.Public
);
//创建一个新对象
T newObject=newt();
//循环浏览所有属性并复制信息
//从源对象到新实例
foreach(PropertyInfo中的p属性)
{
类型t=p.PropertyType;
if((t.IsValueType | | t==typeof(string))&&&(p.CanRead)&(p.CanWrite))
{
p、 SetValue(newObject,p.GetValue(srcObject,null),null);
}
}
//返回克隆的对象。
返回newObject;
}

仅克隆公共属性

var PropertyBindings = BindingFlags.Public | BindingFlags.Instance;
是值类型或字符串

var PropType = p.PropertyType.IsValueType || p.PropertyType == typeof(string);
而且这些都是可访问的

 var IsAccessible = p.CanRead && p.CanWrite;