I do insertion with following in my ASP.NET MVC3 project:
var query = "INSERT INTO MyTable VALUES(//some values)";
db.Database.ExecuteSqlCommand(query);
Is there an easy way to get the inserted row’s ID?
EDIT:
My stored procedure:
CREATE PROCEDURE addGetID
(
@PersonnelID INT,
@ShiftWorkID BIGINT,
@EntranceDateTime DATETIME,
@WorkflowStateRelationID BIGINT
)
AS
INSERT INTO DynamicDataEntrances VALUES (@PersonnelID, @ShiftWorkID, @EntranceDateTime, @WorkflowStateRelationID)
SELECT @@IDENTITY
My code lines:
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;
I agree with [scartag][1] on this one. But to answer your question in 2 parts.
If you’re going to use direct sql then the thing to do is create a stored proc that returns the
@@IDENTITYvalue. Then you exec your Sp with a parameter ofParameterDirection.ReturnValueand use that value.Like such:
Or just use EF. Create and initialize your
Entity, add it to the applicableDbSetand call savechanges. Your Entity instance’s Id column will be updated with the value generated by the database.EDIT 2: I applied the first solution to a local db of mine and could get it to give a return value either. After some research I was able to get a return value. I have a local db with a Blog table. I created an addBlog SP and this is how you can get a return value – but instead of using ExecSqlCommand you must use SqlQuery.
Here’s my SP:
and my EF code: