What is the best way to get IDENTITY
of inserted row?
I know about @@IDENTITY
and IDENT_CURRENT
and SCOPE_IDENTITY
When you use Entity Framework, it internally uses the OUTPUT
technique to return the newly inserted ID value
DECLARE @generated_keys table([Id] uniqueidentifier)
INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID INTO @generated_keys
VALUES('Malleable logarithmic casing');
SELECT t.[TurboEncabulatorID ]
FROM @generated_keys AS g
JOIN dbo.TurboEncabulators AS t
ON g.Id = t.TurboEncabulatorID
WHERE @@ROWCOUNT > 0
The output results are stored in a temporary table variable, joined back to the table, and return the row value out of the table.
Note: I have no idea why EF would inner join the ephemeral table back to the real table (under what circumstances would the two not match).
But that's what EF does.
This technique (OUTPUT
) is only available on SQL Server 2008 or newer.
The reason that Entity Framework joins back to the original table, rather than simply use the OUTPUT
values is because EF also uses this technique to get the rowversion
of a newly inserted row.
You can use optimistic concurrency in your entity framework models by using the Timestamp attribute: