<>asp.Netでデータベースにデータを挿入するとき、現在の挿入行のプライマリ・キーを取得するにはどうすればいいですか?

1377 ワード

データベースの挿入または更新操作を行う場合、現在挿入されているローのデータベース・テーブルのプライマリ・キー値を知る必要がある場合がありますが、どのようにして取得しますか?次のコードは、データを挿入するときのプライマリ・キー値を実現します.
//            ,               

public int Create()

{

  //       

  SqlConnection connection = new SqlConnection(_Connectionstring);

  connection.open();//       

  //         

  SqlCommand command = new SqlCommand("insert into Customers "

   +"(LastName,FirstName,Address,City,State,Zip,Phone,"

   +"SignUpDate) values (@LastName,@FirstName,@Address,"

   +"@City,@Zip,@Phone,@SignUpDate)",connection);

   

   //             

   command.Parameters.AddWithValue("@LastName",_LastName);

   command.Parameters.AddWithValue("@FirstName",_FirstName);

   command.Parameters.AddWithValue("@Address",_Address);

   command.Parameters.AddWithValue("@City",_City);

   command.Parameters.AddWithValue("@Zip",_Zip);

   command.Parameters.AddWithValue("@Phone",_Phone);

   command.Parameters.AddWithValue("@SingUpDate",_SingUpDate);

   

   command.ExecuteNonQuery();//      

   command.Parameters.Clear();

   command.CommandText = "select @@IDENTITY"; //    

   int newCustomerID = Convert.ToInt32(command.ExecuteScalar());

   connection.Close();//    

   _CustomerID = newCustomerID;

   return newCustomerID;   

}