Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将id标识值存储在变量中_C#_Asp.net_Sql Server_Identity - Fatal编程技术网

C# 将id标识值存储在变量中

C# 将id标识值存储在变量中,c#,asp.net,sql-server,identity,C#,Asp.net,Sql Server,Identity,我正在使用ASP.NET、C#和SQL Server 2012 我有一个按钮,它将插入到名为images的表中的新行中,我正在使用标识为image\u id生成一个新的整数id 我还有其他表,它们的外键是image\u id 我想要的是将新生成的image\u id的值存储在一个变量中,然后与其他函数一起使用 我不能使用最后一行值,因为我将与其他按钮一起使用该表,如果它们同时单击,则可能会获取其他按钮的数据 有没有办法将新插入行的确切id保存在变量中 构建一个类并将其存储在类中 public

我正在使用ASP.NET、C#和SQL Server 2012

我有一个按钮,它将插入到名为
images
的表中的新行中,我正在使用
标识
image\u id
生成一个新的整数id

我还有其他表,它们的外键是
image\u id

我想要的是将新生成的
image\u id
的值存储在一个变量中,然后与其他函数一起使用

我不能使用最后一行值,因为我将与其他按钮一起使用该表,如果它们同时单击,则可能会获取其他按钮的数据


有没有办法将新插入行的确切id保存在变量中

构建一个类并将其存储在类中

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

在生成image\u id的代码中,将yourClass.image\u id设置为新值。

在插入新记录时,作为同一批的一部分,也可以调用
scope\u identity()
,并将结果返回给程序。它可能看起来像这样:

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();
}

请注意SQL命令实际上是如何在同一字符串中包含两条语句的

您是否已从数据库返回
id
?此外,我们还需要查看您正在使用的代码,以便提供帮助