首页 文章

深度克隆对象后清除主键

提问于
浏览
2

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

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

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

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

我已经使用this method来做克隆,但我正在寻找 iterating through the parent and children properties 的优雅方式(假设可能有大量子对象,级联远远超过1级)和 setting their primary keys to 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;
    }
    

相关问题