Clearing primary keys after deep cloning an object

I have the following LINQ to SQL objects (for example)

class Parent{
    int id; // primary key
    IEnumerable<Child> children;
}

class Child{
    int id; // primary key 
    string field1;
    int field2;
}

I need to deep clone a Parent and save it to the database but with COPIES of the children ie NOT referencing the existing children.

I have used this method to do the clone, but am looking for an elegant way of iterating through the parent and children properties (given that there could be a large number of child objects, cascading much further than 1 level deep) and setting their primary keys to 0 so that when I submit the cloned object to the database, LINQ to SQL takes care of creating the new children.


您可以尝试使用System.Reflection的以下扩展方法:

public static T DeepCopy<T>(this T parent) where T : new()
{
    var newParent = new T();
    foreach (FieldInfo p in typeof(T).GetFields())
    {
        if (p.Name.ToLower() != "id")
            p.SetValue(newParent, p.GetValue(parent));
        else
            p.SetValue(newParent, 0);
        if (p.FieldType.IsGenericType &&
            p.FieldType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        {
            dynamic children = p.GetValue(parent);
            dynamic newChildren = p.GetValue(parent);
            for (int i = 0; i < children.Length; i++)
            {
                var newChild = DeepCopy(children[i]);
                newChildren.SetValue(newChild, i);
            }
        }
    }
    return newParent;
}
链接地址: http://www.djcxy.com/p/6970.html

上一篇: 对象被克隆,但静态引用仍然存在?

下一篇: 深度克隆对象后清除主键