NotDan
NotDan

Reputation: 32223

NHibernate FlushMode on Save

I have set the FlushMode property on an NHibernate session to FlushMode.Never, but when I call session.Save(User), a call gets made to the database anyway. Is this how this is supposed to work? I would think that it shouldn't do an insert until I call Flush().

Edit: I found the issue, I changed the primary key to guid and it worked. Are there any other types (i.e. no guid primary key) that will work? I would rather have a number instead of a guid...

Upvotes: 4

Views: 4967

Answers (3)

sirrocco
sirrocco

Reputation: 8055

Try wrapping the session.Save(User) in a transaction and set the FlushMode to Commit.

That should assure that no calls are made to the db.

Upvotes: -1

Jorge Alves
Jorge Alves

Reputation: 1168

You were using a native generator, right?

The problem with this lies in the fact that, since it's the DB that generates the ID, NHibernate needs a round trip to fetch it. As an example, for Server's identity fields the actual INSERT statement must be executed before SCOPE_IDENTITY() returns a valid key. And the only way to perform this operation safely is by flushing the session.

As an alternative to guids and identity you can try the "increment" generator to see if it fits your needs: http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/mapping.html#mapping-declaration-id-generator

You should be aware that this approach won't be feasible if you cluster your app, or you have some other process or application inserting into the same table.

PS: for further reading try http://unhandled-exceptions.com/blog/index.php/2008/12/11/on-choosing-an-identity-type/

Upvotes: 8

NotDan
NotDan

Reputation: 32223

I found the issue, I was using an identity as the primary key. Changing it to guid worked.

Upvotes: 1

Related Questions