Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate get Id of saved object

I'm using Fluent NHibernate in an Asp.net MVC application. I have it set up to start a session and transaction on every request, and commit the transaction at the request end. However, what I want to do is save an object (in this case, a new "Company") and then redirect to that new Company's detail page. How do I get the Id of the new company so that I can redirect? If I get the Id after session.Save(company), it is null. This makes sense as it hasn't yet been committed, however, it still seems there should be a relatively easy way to do this without committing the current transaction and starting a new one.

like image 490
Matthew Talbert Avatar asked Feb 11 '10 06:02

Matthew Talbert


1 Answers

NHibernate generates an id when session.Save() or session.SaveOrUpdate() is called with an transient entity. At this time, the id property of the entity is set and can be used.

If the id generator requires database access, it will happen at this time. So for the Identity generator, the insert will be performed at this time as will any pending inserts.

Otherwise, the insert is pending until the session is flushed which will happen:

  • from some invocations of Find() or Enumerable()
  • from NHibernate.ITransaction.Commit()
  • from ISession.Flush()
like image 153
Lachlan Roche Avatar answered Oct 31 '22 17:10

Lachlan Roche