【问题标题】:Clearing primary keys after deep cloning an object深度克隆对象后清除主键
【发布时间】:2013-07-17 02:09:58
【问题描述】:

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

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

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

我需要深度克隆 Parent 并将其保存到数据库中,但要使用子级的副本,即不引用现有的子级。

我已经使用this method 进行克隆,但我正在寻找一种优雅的方式来迭代父和子属性(考虑到可能存在大量子对象,级联远超过 1 级)并将它们的主键设置为 0,这样当我将克隆的对象提交到数据库时,LINQ to SQL 会负责创建新的子对象。

【问题讨论】:

    标签: c# linq-to-sql reflection clone


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2010-09-09
      • 2012-06-05
      • 2013-09-06
      • 2013-10-11
      • 2018-03-21
      • 2019-03-25
      • 1970-01-01
      相关资源
      最近更新 更多