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


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

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




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


你使用哪个身份生成器?如果您使用后插入生成器(如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

  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)