繁体   English   中英

深度克隆对象后清除主键

[英]Clearing primary keys after deep cloning an object

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

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

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

我需要深度克隆一个Parent并将其保存到数据库,但是使用子节点的COPIES,即不引用现有的子节点。

我已经使用这种方法来做克隆,但我正在寻找一种优雅的方法来迭代父和子属性 (假设可能有大量子对象,级联远远超过1级)并设置它们的主要键为0,以便在将克隆对象提交到数据库时,LINQ to SQL负责创建新子项。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM