Reputation: 472
I need to know how can I know what is the last inserted id in a SQL Server database for a given table?
I'm using int identity
not guid and if it's matters NHibernate as my ORM.
Thanks
Upvotes: 2
Views: 2077
Reputation: 2391
You could try something like this:
var sql = "SELECT IDENT_CURRENT('TableName')";
var query = session.CreateSQLQuery(sql);
var result = query.UniqueResult();
This will return the last identity value generated for a given table.
Upvotes: 5
Reputation: 65097
Depending on how your ID's are generated, you should be able to return it straight from the ISession.Save()
:
int insertedID = (int)session.Save(entity);
Upvotes: 4