NHibernate ISession.Save() – 为什么这会立即持续存在于我的实体中?

我正在使用NHibernate创建大量实体,将它们附加到我的ISession,然后使用事务将我的更改提交到数据库.代码示例如下:

ISession _context = SessionProvider.OpenSession();

//Create new entities
for(int i=0; i<100; i++)
{
    MyEntity entity = new MyEntity(i);

    //Attach new entity to the context
    _context.Save(entity);
}

//Persist all changes to the database
using(var tx = _context.BeginTransaction())
{
    //Flush the session
    tx.Commit();
}

我的印象是_context.Save()行只是让ISession知道新实体,但是在我通过tx.Commit()行刷新会话之前,没有任何更改持久存储到数据库.

我观察到的是,每次调用_context.Save()时数据库都会获得一个新实体.因此,我最终会对数据库进行过多的单独调用.

有谁知道为什么ISession.Save()会自动持久更改?我是否误解了NHibernate的行为方式?谢谢.

***编辑 – 只是为了澄清(根据两个建议的答案) – 我的问题是,一旦我调用_context.Save(),数据库就会更新.我不指望这会发生.我希望在调用tx.Commit()之前不要将任何内容插入到数据库中.到目前为止,两个建议的答案都没有帮助解决这个问题.

关于身份生成器的一些好信息可以在here找到

你使用哪个身份生成器?如果您使用后插入生成器(如MSSQL / MySQL的Identity或Oracle的序列)来生成Id字段的值,那么这就是您的问题.

NHibernate POID Generators Revealed开始:

Post insert generators, as the name
suggest, assigns the id’s after the
entity is stored in the database. A
select statement is executed against
database. They have many drawbacks,
and in my opinion they must be used
only on brownfield projects. Those
generators are what WE DO NOT SUGGEST
as NH Team
.

Some of the drawbacks are the
following

  1. Unit Of Work is broken with the use of
    those strategies. It doesn’t matter if
    you’re using FlushMode.Commit, each
    Save results in an insert statement
    against DB. As a best practice, we
    should defer insertions to the commit,
    but using a post insert generator
    makes it commit on save (which is what
    UoW doesn’t do).
  2. Those strategies nullify batcher, you can’t take the advantage of sending multiple queries at once(as it must go to database at the time of Save)
相关文章
相关标签/搜索