tags:

views:

39

answers:

3

Howdy,

So I've got a simple table with an ID field that's incrementally generated on INSERT.

I've set the mapping up in NHibernate to reflect this:

<id name="ID">
  <generator class="identity" />
</id>

And it all works fine.

Trouble is, I need to get the generated ID after I've saved a new model to use elsewhere:

var model = new MyModel();
session.SaveOrUpdate(model);

But at this stage model.ID == null, not the ID.

Any ideas?

Anthony

+1  A: 

As far as I understand the identities are generated by the database, and since SaveOrUpdate() does not actually save your Model, the ID will be null. This should change once you commit the content of your session to the DB.

FrontSvin
+3  A: 

You need to flush the session so that changes are persisted to the database. You can do this by calling session.Flush() or, better yet, using a transaction:

using (var txn = session.BeginTransaction())
{
    session.SaveOrUpdate(model);
    txn.Commit();
}
Jamie Ide
A: 

If you set Name property in mappings then NHibernate will set Id for you after it saves entity

Sly