English 中文(简体)
把Linq改为Sql实体——删除数据背景
原标题:Cloning a Linq to Sql Entity - detaching data context

我必须把Linq打到SQ。 概述:

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()是一种简单的通用方法,用于将原始实体的数据复制给新实体。

我的问题是,当我尝试把新实体重新输入数据库时,我有以下错误:

已经尝试向Atach或Add一个不是新实体,或许是从另一个数据目录中装出的。 这没有得到支持。

我似乎难以找到一种从数据角度去除受污名的实体的容易/遗传的方法。 或者,我是否可以调整我的克隆方法,以ski熟相关领域?

Can anyone point me in the right direction?

感谢。

为了完整起见,我最后提出以下马库斯建议:

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);

And that are accessible

 var IsAccessible = p.CanRead && p.CanWrite;
问题回答

暂无回答




相关问题
LINQ to SQL as databinding source for WPF Treeview

I wonder if someone could provide a simple example of the following. (preferably in VB.Net): I have an SQL database with related tables and I am successfully using LINQ to SQL in other areas of my ...

Linq to SQL insert/select foreign/primary records

I have table A and Table B. Table B contains two columns, Name and ID. Table A contains several columns and a foreign key column pointing to B.ID called B_ID On the client side, I have all the data I ...

LINQ to SQL Dynamic Sort question

How do I code the Select clause in my LINQ satament to select column aliases so I can sort on them basically I want to accomplish this SQL statement in LINQ: select type_id as id, ...

Using a schema other than dbo in LinqToSql Designer

Is there a way to specify in a data connection or the LinqToSql Designer a schema? Whenever I go to setup a data connection for LinqToSql there doesn t seem to be anyway to specify a schema and I ...

热门标签