简体   繁体   English

last_insert_id? C#,SQL Server和NHibernate

[英]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? 我需要知道如何知道给定表的SQL Server数据库中最后插入的id是什么?

I'm using int identity not guid and if it's matters NHibernate as my ORM. 我使用的是int identity而不是guid,如果将NHibernate作为我的ORM则很重要。

Thanks 谢谢

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. 这将返回为给定表生成的最后一个标识值。

根据您的ID的生成方式,您应该可以直接从ISession.Save()返回它:

int insertedID = (int)session.Save(entity);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM