简体   繁体   English

在NHibernate中克隆实体?

[英]Cloning an entity in NHibernate?

I want to save a single object to the database twice. 我想将一个对象保存到数据库两次。 I have this code: 我有以下代码:

using (var ss = NHibHelp.OpenSession())
using (var tt = ss.BeginTransaction())
{
    var entity = new Entity();

    ss.Save(entity);
    ss.Save(entity);

    tt.Commit();
}

But this results in only one row being added to the database. 但这导致仅一行被添加到数据库。 How do I insert a single object into the database twice (with two different Ids) ? 如何将一个对象两次插入数据库(具有两个不同的ID)?

You shouldn't do this - NHibernate maintains "object identity" within it's session, so it will not differentiate between ..well.. the same object. 您不应该这样做-NHibernate在其会话中维护“对象标识”,因此它不会区分..well ..同一对象。 I would really advise against this, and a better solution would be to look at a way of cloning the object (either via reflection, or a Clone method), and then saving the cloned object. 我真的建议不要这样做,更好的解决方案是研究一种克隆对象的方法(通过反射或Clone方法),然后保存克隆的对象。

If you want to ignore my advice above, you can get it to work by evicting the entity from the session, setting it's id back to it's unsaved value (depends on your mapping, but probably 0), and then saving it again. 如果您想忽略上述建议,可以通过将实体从会话中逐出,将其ID设置回未保存的值(取决于您的映射,但可能为0),然后再次保存来使其正常工作。

It might also work if you just called session.Merge(entity) twice (you probably have to reset the id to it's unsaved value after the first call). 如果您仅两次调用了session.Merge(entity),它也可能会起作用(您可能必须在第一次调用后将ID重置为未保存的值)。

Alternatively you could use a stateless session with session.Merge() and then you don't have to evict the entity between Save's. 或者,您可以将无状态会话与session.Merge()一起使用,然后不必在保存对象之间逐出该实体。

You can do it in two ways: 您可以通过两种方式进行操作:

  1. Clone the entity, should be a deep copy. 克隆实体,应该是深层副本。

     using (var ss = NHibHelp.OpenSession()) using (var tt = ss.BeginTransaction()) { var entity = new Entity(); var clonedEntity = entity.Clone(); ss.Save(entity); ss.Save(clonedEntity); tt.Commit(); } 

If your ID is assigned, remember to create a new ID. 如果分配了您的ID,请记住创建一个新ID。 Deep copy have some issues with complex entities, if you have inverted collection you need to re-reference them. 深层复制在复杂实体方面存在一些问题,如果您有反向集合,则需要重新引用它们。

2.Open a second transaction in a new session and commit it. 2.在新会话中打开第二个事务并提交。

var entity = new Entity();
using (var ss = NHibHelp.OpenSession())
using (var tt = ss.BeginTransaction())
{      
     ss.Save(entity);

     tt.Commit();
}

using (var ss = NHibHelp.OpenSession())
using (var tt = ss.BeginTransaction())
{      
     ss.Save(entity);

     tt.Commit();
}

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

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