深度克隆一个对象后清除主键

3

我有以下LINQ to SQL对象(例如)

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

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

我需要深度克隆一个Parent并将其保存到数据库中,但是需要子项的副本,即不引用现有的子项。
我已经使用这种方法来进行克隆,但是我正在寻找一种优雅的方式来迭代父对象和子对象属性(考虑到可能有大量的子对象,级联深度可能超过1级),并将它们的主键设置为0,以便在将克隆的对象提交到数据库时,LINQ to SQL会负责创建新的子对象。
1个回答

2
您可以尝试以下使用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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接