Grunf
Grunf

Reputation: 472

last_insert_id ? C#, SQL Server and NHibernate

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

Answers (2)

Sean Amos
Sean Amos

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

Simon Whitehead
Simon Whitehead

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

Related Questions