加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 07:26:17 所属栏目:MsSql教程 来源:网络整理
导读:我需要克隆 Linq to SQL实体.概述: Customer origCustomer = db.Customers.SingleOrDefault(c = c.CustomerId == 5);Customer newCustomer = CloneUtils.Clone(origCustomer);newCustomer.CustomerId = 0; // Clear keydb.Customers.InsertOnSubmit(newCusto
我需要克隆 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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读