在'Using'语句中选择@@ Identity

Mik*_*ter 0 c# using sql-server-ce

我正在编写一个Sql-Server-ce应用程序C#.

最近我一直在将我的代码转换为使用using语句,因为它们更清晰.在我的代码中,我有一个GetLastInsertedID非常简单的函数 - 它返回最后插入的ID.工作版本如下:

    public static int GetLastInsertedID()
    {
        int key = 0;
        try
        {
            SqlCeCommand cmd = new SqlCeCommand("SELECT CONVERT(int, @@IDENTITY)", DbConnection.ceConnection);
            key = (int)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Could not get last inserted ID. " + ex.Message);
            key = 0;
        }
        return key;
    }
Run Code Online (Sandbox Code Playgroud)

下面的代码在我将它包装在using语句中后不起作用:

    public static int GetLastInsertedID()
    {
        int key = 0;
        try
        {
            using (SqlCeConnection conn = new SqlCeConnection(DbConnection.compact))
            {
                conn.Open();
                using (SqlCeCommand cmd = new SqlCeCommand("SELECT CONVERT(int, @@IDENTITY)", conn))
                    key = (int)cmd.ExecuteScalar();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Could not get last inserted ID. " + ex.Message);
            key = 0;
        }
        return key;
    }
Run Code Online (Sandbox Code Playgroud)

我得到的错误是specified cast is not valid.虽然这个错误通常是不言自明的,但我不明白为什么我会在第二个代码块中获取它,而不是第一个.该错误发生在该行上key = (int)cmd.ExecuteScalar();.

我在第二块代码中做错了什么?

flu*_*lup 5

@@ IDENTITY文档:

@@ IDENTITY和SCOPE_IDENTITY将返回当前会话中任何表中生成的最后一个标识值.

我认为您的更改现在为每个using语句启动一个新会话.因此@@ IDENTITY为空.