SCOPE_IDENTITY() with LINQ

While reading about a recent question concerning @@Identity and the reasons to use SCOPE_IDENTITY() instead I experimented with LINQ to get the SCOPE_IDENTITY() results.

 using (var dbc = new siteDataContext())
    {
        dbc.Log = Console.Out;
        repertoire newSkill = new repertoire
            {
                skill = "a new item"
            };
        dbc.repertoires.InsertOnSubmit(newSkill);
        dbc.SubmitChanges();
        Console.Write(newSkill.id.ToString());
    }

It seems that calling the id column of the inserted object gives you the SCOPE_IDENTITY(). Here is the SQL Log:

INSERT INTO [dbo].[repertoire]([skill])
VALUES (@p0)
SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]
-- @p0: Input NVarChar (Size = 10; Prec = 0; Scale = 0) [a new item]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

Leave a Reply

Your email address will not be published. Required fields are marked *