代码之家  ›  专栏  ›  技术社区  ›  Charlie Bear

在nhibernate中复制对象图并作为新对象持久化

  •  2
  • Charlie Bear  · 技术社区  · 17 年前

    我有一个具有各种属性的manager对象和一组受管员工。这与数据库中的两个表有关,其中员工通过外键链接到经理。

    我正在使用nhibernate,想知道是否有一种巧妙的方法来做到这一点。

    我唯一能想到的方法是手动:

    manager old = getManager(); // get the original for copying 
    
    manager newManager = new manager(); // create a blank object
    newManager .name = old.name //give the new manager the old one's props;
    
    //cycle through the staff duplicate and add to new managers staff collection
    foreach(staff s in old.staffCollection)
    {
      staff newStaff = new staff();
      newstaff.name = s.name;
      newManager.staffCollection.Add(newstaff); 
    }
    

    1 回复  |  直到 17 年前
        1
  •  0
  •   JoshBerke    17 年前

    如果将实体标记为可序列化,则可以进行二进制序列化。

       public static MemoryStream Serialize(object data)
        {
    
            MemoryStream streamMemory = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.AssemblyFormat = FormatterAssemblyStyle.Simple;
    
            formatter.Serialize(streamMemory, data);
    
            return streamMemory;
        }
        public static Object Deserialize(MemoryStream stream)
        {
    
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.AssemblyFormat = FormatterAssemblyStyle.Simple;
            return formatter.Deserialize(stream);
    
        }
    

    从本质上讲,您将调用Serialize,然后调用DeSerialize方法,这将为您提供图形的深度副本,然后您必须更新您可能拥有的任何ID。