There is a GetLastInsertId method in WebMatrix. However, using Reflector, I can see that it's implemented like this:
[return: Dynamic]
public object GetLastInsertId()
{
return this.QueryValue("SELECT @@Identity", new object[0]);
}
Which, as far as I can see, is a very bad way of doing it, because @@Identity
returns the last insert considering every table and every session. I need this restricted to the scope and session I'm working with, so I was expecting this to use SELECT SCOPE_IDENTITY()
, since that also seems to be what is most often used according to my reading.
My questions are:
I am interested in answers for SQL Server (not compact) if that makes a difference.
I had the same problem, and I read these answers but still couldn't get the code to work correctly. I possibly was misreading the solutions above, but what seemed to work for me was as follows:
var db=Database.Open(...);
var lastInsertID = db.QueryValue("INSERT name into Names; SELECT SCOPE_IDENTITY()");
here is my solution
var db.Database.open('..');
var lastId = db.GetLastInsertId();
To quote David Fowler , one of the devs on the Data APIs in WebMatrix: "[SCOPE_IDENITTY] doesn't work on ce". Since we wanted a data API that would work on both CE and regular SQL Server, we used @@Identity. So if you want to use SCOPE_IDENTITY specifically, you should use db.QueryValue method:
var db = Database.Open(...);
db.Insert(...);
var lastInsertId = db.QueryValue("SELECT SCOPE_IDENTITY()")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.