im writing a library database program. It can insert books, but I have a problem in making a reference between book and a person which rents it. I can't get a last inserted id from a rents table to put it to the compilation table to assign book to a person who rents it. I've tried SCOPE_IDENTITY() but it doesn't works for me. Here's the code:
private void addRentButton_Click(object sender, EventArgs e) {
elibrary f1 = new elibrary();
string query = "INSERT INTO rents VALUES (@renterName, @rentStartDate, @rentEndDate)";
using(f1.Connection = new SqlConnection(f1.connectionString))
using(SqlCommand command = new SqlCommand(query, f1.Connection)) {
f1.Connection.Open();
command.Parameters.AddWithValue("@renterName", rentNameBox.Text);
command.Parameters.AddWithValue("@rentStartDate", DateTime.Now);
command.Parameters.AddWithValue("@rentEndDate", rentEndDatePicker.Value);
command.ExecuteScalar();
}
rentEndDatePicker.Value = DateTime.Now;
string Compilationquery =" INSERT INTO compilation VALUES (@bookId, SELECT SCOPE_IDENTITY())";
using(f1.Connection = new SqlConnection(f1.connectionString))
using(SqlCommand command = new SqlCommand(Compilationquery, f1.Connection)) {
f1.Connection.Open();
command.Parameters.AddWithValue("@bookId", f1.listBook.SelectedValue);
command.ExecuteScalar();