ASP.net DAL获取刚刚插入的记录的ID

时间:2011-01-28 17:36:43

标签: c# asp.net data-access-layer uniqueidentifier

        // Add into DB
        int recordID = 0;
        using (tblArtworkTemplatesTableAdapter tblAdapter = new tblArtworkTemplatesTableAdapter())
        {
            tblAdapter.Insert(DateTime.Now, int.Parse(lstChooseSpec.SelectedValue), Master.loginData.loggedInUser.ID);
            recordID = int.Parse(tblAdapter.GetLastID().ToString());
        }

        // Redirect
        Response.Redirect("artworkDesigner.aspx?ID=" + recordID);

它正在调用的存储过程是:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetLastID]
AS
    SET NOCOUNT ON;
select @@identity FROM tblArtworkTemplates

我似乎无法让它工作,我对这个DAL的东西感兴趣,任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

我猜这是SQL Server?您应该从INSERT INTO存储过程返回新插入记录的ID。有关@@Identity的更多信息,请参阅@@IDENTITY (Transact-SQL)

从存储过程返回新插入记录的ID:

SELECT ID AS LastID FROM tblArtworkTemplates WHERE ID = @@Identity; 

有关该主题的更多信息,请参阅How To Get Last Inserted ID On SQL Server