【问题标题】:duplicate object graph and persist back as new in nhibernate复制对象图并在 nhibernate 中作为新对象持久存在
【发布时间】:2009-03-19 17:47:05
【问题描述】:

我想创建“以前的版本”,以便用户可以撤消所做的更改并回滚到以前的版本。

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

我想要做的是复制经理和他的所有员工并将其保存回数据库作为经理表中的新条目和员工表中与新经理相关的一系列新条目.

我正在使用 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); 
}

上面的例子并不完全是我的做法,但你明白了我希望的想法。

我考虑过使用反射来获取道具,而不是手动设置它们,但这和我一样聪明。

在 nhibernate 中有没有办法复制对象图并将其作为新条目保留回来?

或者有人有什么好主意吗??

【问题讨论】:

  • 我知道这只是示例代码,但我真的希望你的 managerstaff 类名不是真的小写!

标签: nhibernate


【解决方案1】:

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

   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。

请注意,我不确定这将如何与 nHibernates 延迟加载功能一起使用。我已经做了很多,但不是我从 nHibernate 中提取的对象。也不要忘记将 Serializable 放在你的对象上。

【讨论】:

  • 我收到一个错误 System.Runtime.Serialization.SerializationException:在程序集“NHibernate,版本=1.2.1.4000,文化=中性,PublicKeyToken=aa95f207798dfdb4”中键入“NHibernate.Cfg.Configuration”作为可序列化的。我也不能将其标记为可序列化?
  • 不,你不应该,你的对象没有任何引用,或者 Session 或 SessionFactory 是吗?
  • 一些静态方法可以。例如,我有 manager.create(newManager)。我想你会告诉我我应该使用 repo 模式并停止对我的实体进行 ref nhibernate?
  • 是的,我会告诉你:-) 但是静态方法不应该这样做。你在使用延迟加载吗?您可以尝试关闭延迟加载...
  • 嗯,我不是延迟加载。我想我需要尝试找到隐藏的引用...
猜你喜欢
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多