7

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 から読み込まれた可能性がある、新しくないエンティティをアタッチまたは追加しようとしました。これはサポートされていません。

複製されたエンティティをデータ コンテキストから切り離す簡単で一般的な方法が見つからないようです。または、クローン作成方法を調整して、コンテキスト関連のフィールドを「スキップ」することはできますか?

誰かが私を正しい方向に向けることができますか?

ありがとう。

完全を期すために、マーカスのアドバイスに従って最終的に得た方法を次に示します。

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;
}
4

1 に答える 1

6

パブリックプロパティのクローンのみ

var PropertyBindings = BindingFlags.Public | BindingFlags.Instance;

それは値型または文字列です

var PropType = p.PropertyType.IsValueType || p.PropertyType == typeof(string);

そしてそれはアクセス可能です

 var IsAccessible = p.CanRead && p.CanWrite;
于 2012-01-12T21:17:52.300 に答える