我需要克隆
Linq to 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加载.这不受支持.
我似乎无法找到一种从数据上下文中分离克隆实体的简单/通用方法.或者我可以调整克隆方法以“跳过”与上下文相关的字段?
谁能指出我正确的方向?
谢谢.
为了完整起见,这是我最终遵循Marcus的建议的方法:
- 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;
- }
解决方法
仅克隆公共属性
- var PropertyBindings = BindingFlags.Public | BindingFlags.Instance;
这是值类型或字符串
- var PropType = p.PropertyType.IsValueType || p.PropertyType == typeof(string);
这是可以访问的
- var IsAccessible = p.CanRead && p.CanWrite;