Storing the id identity value in a variable

Viewed 523

I am using ASP.NET, C#, and SQL Server 2012.

I have a button that will insert into a new row in a table called images, and I am using an identity to generate a new integer id for the image_id.

I also have other tables with the image_id as a foreign key.

What I want is to store the value of the newly generated image_id in a variable and use it later with other functions.

I can't use the last row value since I will use the table with other buttons and if they clicked at the same time they might get the other's data.

Is there a way to save the exact id of the newly inserted row in a variable?

2 Answers

At the time you insert a new record, as part of the same batch, also call scope_identity() and return that result back to your program. It might look something like this:

int newIDValue;
using (var cn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand("INSERT INTO [table] (...) VALUES (...); SELECT scope_idenity;"))
{
    cn.Open();
    newIDValue = (int)cmd.ExecuteScalar();
}

Note how the SQL command is actually two statements in the same string.

Build a class and store it in the class.

 public class yourClass
 {
    private int image_id;
    public int Image_id
    {
        get
        {
            return image_id;
        }
        set
        {
            image_id= value;
        }
    }
 }

In your code where you generate the image_id, set yourClass.Image_id to the new value.

Related