2012-01-12 21 views
7

Tôi có yêu cầu sao chép thực thể LINQ to SQL. Tổng quan:Nhân bản một LINQ thành thực thể SQL - tách bối cảnh dữ liệu

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 

nơi CloneUtils.Clone() là một phương pháp chung đơn giản sử dụng phản ánh sao chép dữ liệu từ thực thể gốc sang thực thể mới.

Tôi có vấn đề là khi tôi cố gắng và thêm các thực thể mới trở lại vào cơ sở dữ liệu, tôi nhận được lỗi sau:

Một cố gắng đã được thực hiện để Đính kèm hoặc Thêm một thực thể đó không phải là mới, có lẽ đã được tải từ một DataContext khác. Điều này không được hỗ trợ.

Tôi dường như không thể tìm ra cách dễ dàng/chung chung để tách thực thể nhân bản khỏi ngữ cảnh dữ liệu. Hoặc có lẽ tôi có thể điều chỉnh phương pháp nhân bản của tôi để 'bỏ qua' các lĩnh vực liên quan đến bối cảnh?

Có ai có thể chỉ cho tôi đúng hướng không?

Cảm ơn.

Để hoàn chỉnh, đây là phương pháp tôi đã kết thúc với sau lời khuyên của 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; 
} 

Trả lời

6

Chỉ sao chép tài sản công cộng

var PropertyBindings = BindingFlags.Public | BindingFlags.Instance; 

Đó là kiểu giá trị hoặc chuỗi

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

Và có thể truy cập

var IsAccessible = p.CanRead && p.CanWrite; 
+0

Cảm ơn bạn Marcus - đã hoạt động hoàn hảo – Neilski

Các vấn đề liên quan