我在我的 ASP.NET MVC3 项目中插入以下内容:
var query = "INSERT INTO MyTable VALUES(//some values)";
db.Database.ExecuteSqlCommand(query);
有没有一种简单的方法来获取插入行的 ID?
编辑:
我的存储过程:
CREATE PROCEDURE addGetID
(
@PersonnelID INT,
@ShiftWorkID BIGINT,
@EntranceDateTime DATETIME,
@WorkflowStateRelationID BIGINT
)
AS
INSERT INTO DynamicDataEntrances VALUES (@PersonnelID, @ShiftWorkID, @EntranceDateTime, @WorkflowStateRelationID)
SELECT @@IDENTITY
我的代码行:
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
SqlParameter PersonnelID = new SqlParameter("@PersonnelID", 1);
SqlParameter ShiftWorkID = new SqlParameter("@ShiftWorkID", 2);
SqlParameter EntranceDateTime = new SqlParameter("@EntranceDateTime", dt);
SqlParameter WorkflowStateRelationID = new SqlParameter("@WorkflowStateRelationID ", db.WorkflowStateRelations.Where(wsr => wsr.WorkflowID == dp.WorkflowID).Select(x => x.ID).FirstOrDefault());
SqlParameter returnValue = new SqlParameter();
returnValue.Direction = ParameterDirection.ReturnValue;
// try 1
db.Database.ExecuteSqlCommand("addGetID(@PersonnelID, @ShiftWorkID, @EntranceDateTime, @WorkflowStateRelationID )", PersonnelID, ShiftWorkID, EntranceDateTime, WorkflowStateRelationID, returnValue);
// try 2
db.Database.ExecuteSqlCommand("addGetID @PersonnelID @ShiftWorkID @EntranceDateTime @WorkflowStateRelationID ", PersonnelID, ShiftWorkID, EntranceDateTime, WorkflowStateRelationID, returnValue);
// try 3
db.Database.ExecuteSqlCommand("exec addGetID @PersonnelID={0} @ShiftWorkID={1} @EntranceDateTime={2} @WorkflowStateRelationID={3} ", PersonnelID, ShiftWorkID, EntranceDateTime, WorkflowStateRelationID, returnValue);
var id = returnValue.Value;