'Why "LAST_INSERT_ID()" doesn't return anything here in a MySQL reader?
I am trying to understand why the second LAST_INSERT_ID() command doesn't return anything in the reader after executing addInvoiceCommand. The reader keeps returning 0 rows. The first reader after addClientCommand works fine.
using (var connection = new MySqlConnection(builder.ConnectionString))
{
await connection.OpenAsync();
var addClientCommand = connection.CreateCommand();
addClientCommand.CommandText = @"INSERT INTO client(clientName)
VALUES(@ClientName);";
addClientCommand.Parameters.AddWithValue("@ClientName", input.Client.ClientName);
addClientCommand.ExecuteNonQueryAsync();
var selectLastIdCommand = connection.CreateCommand();
string lastInsertedId = "";
selectLastIdCommand.CommandText = @"SELECT LAST_INSERT_ID();";
using var reader = await selectLastIdCommand.ExecuteReaderAsync();
while (reader.Read())
{
lastInsertedId = reader[0].ToString();
}
reader.Close();
var addInvoiceCommand = connection.CreateCommand();
addInvoiceCommand.CommandText = @"INSERT INTO invoice(client_id,
description, paymentTerms, invoiceDate, paymentDueDate,BillFromAddress,
BillFromCity, BillFromCountry, BillFromPostal)
VALUES(@client_id, @Description, @PaymentTerms, @InvoiceDate, @PaymentDueDate,
@BillFromAddress, @BillFromCity, @BillFromCountry, @BillFromPostal);";
addInvoiceCommand.Parameters.AddWithValue("@client_id", Int32.Parse(lastInsertedId));
addInvoiceCommand.Parameters.AddWithValue("@description", input.Description);
addInvoiceCommand.Parameters.AddWithValue("@paymentTerms", input.PaymentTerms);
addInvoiceCommand.Parameters.AddWithValue("@invoiceDate", input.InvoiceDate);
addInvoiceCommand.Parameters.AddWithValue("@paymentDueDate", input.PaymentDue);
addInvoiceCommand.Parameters.AddWithValue("@BillFromAddress", input.BillFromAddress);
addInvoiceCommand.Parameters.AddWithValue("@BillFromCity", input.BillFromCity);
addInvoiceCommand.Parameters.AddWithValue("@BillFromCountry", input.BillFromCountry);
addInvoiceCommand.Parameters.AddWithValue("@BillFromPostal", input.BillFromPostal);
addInvoiceCommand.ExecuteNonQueryAsync();
var lastInvoiceIdCommand = connection.CreateCommand();
string lastInvoiceId = "";
lastInvoiceIdCommand.CommandText = @"SELECT LAST_INSERT_ID();";
using var readerLastInvoiceId = await lastInvoiceIdCommand.ExecuteReaderAsync();
while (readerLastInvoiceId.Read())
{
lastInvoiceId = reader[0].ToString();
}
readerLastInvoiceId.Close();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
