问题
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:
- Do the WebMatrix wrappers do something that makes this ok to use in my case?
- If not, is there a simple way to get the inserted ID of an insert query using WebMatrix classes, or should I fall back on stuff like SqlClient for this?
I am interested in answers for SQL Server (not compact) if that makes a difference.
回答1:
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()")
回答2:
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()");
回答3:
here is my solution
var db.Database.open('..');
var lastId = db.GetLastInsertId();
来源:https://stackoverflow.com/questions/7753037/how-to-get-inserted-row-id-with-webmatrix