Hi all,
My question is how to get the next id using NHibernate in a mysql db for an auto-increment ID column ?
Thanks,
Hi all,
My question is how to get the next id using NHibernate in a mysql db for an auto-increment ID column ?
Thanks,
You're going to create a race condition if you do this. To answer your question, I don't think there is a specific way for Hibernate to give you this information since no application can give you this information. By getting the "next id", by the time it returns that data to you, it might be invalid already. The easiest way I can think of is to get the last_insert_id() and add +1 to it.
Why don't you post more information about you're trying to accomplish and we can find a better solution for you?
Based on the further description you give (as an answer?) below it seems to me that you are indeed looking for the NHibernate feature to automatically read back IDs generated by the database: identity
This will tell NHibernate the ID's value is determined by the database upon insert, it will not send a value as part of its INSERT statement and it will read back the value of the ID column after it has performed the insert. But you do have to tell the database (in the table definition) that it should auto-generate a value for the ID column for each record inserted...
Provided that you are the only writer to your database then you could get your application to maintain the sequence number for you and allocate the next number yourself.
If you want to do this then you'll want to ensure that your application counter is thread safe.
You'll also want a way to get the last written sequence number when restarting you application.
thank you for your answers, I will try to explain more my question. I'm working on an C# application using NHibernate, and i'm new with it. I'm using a third party GridControl which allow end-user to add, update and delete rows. i will use a simple entity "Contact" to illustrate my question. When i want to update a row i use
contact.ContactID = Column["IDContact"].Value ;
transaction.Commit() ;
but when i want to add a new entry, the GridControl initialize the IDColumn with -1 and when i want to insert it into the db and exception fire (it's normal). so how can I insert a new row in db with an appropriate ID?