将Linq克隆到Sql实体 - 分离数据上下文
问题描述:
我有一个要求将Linq克隆到SQL实体。在概述:将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;
}
答
只克隆公共属性
var PropertyBindings = BindingFlags.Public | BindingFlags.Instance;
这是值类型或字符串
var PropType = p.PropertyType.IsValueType || p.PropertyType == typeof(string);
那可以访问
var IsAccessible = p.CanRead && p.CanWrite;
谢谢马库斯 - 完美的工作 – Neilski 2012-01-13 08:51:49