Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate FlushMode on Save

Tags:

c#

nhibernate

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...

like image 532
NotDan Avatar asked Jan 23 '23 22:01

NotDan


1 Answers

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/

like image 173
Jorge Alves Avatar answered Jan 26 '23 10:01

Jorge Alves