linq-to-sql – 将Linq克隆到Sql实体 – 分离数据上下文
发布时间:2020-05-24 04:17:41 所属栏目:MsSql 来源:互联网
导读:我需要克隆 Linq to SQL实体.概述: Customer origCustomer = db.Customers.SingleOrDefault(c = c.CustomerId == 5);Customer newCustomer = CloneUtils.Clone(origCustomer);newCustomer.CustomerId = 0; // Clear keyd
|
我需要克隆 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; (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
