I want to get the highest ID number in the table and increment it but it seems to return 0 with how i'm doing it.
private int MaxAuthorValue()
{
string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Library;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string maxQuery = "SELECT MAX(AuthorId) FROM Author";
SqlCommand command = new SqlCommand(maxQuery, connection);
int x = (int)command.ExecuteScalar();
return x + 1;
}
}
What I want to do with this is return the inremented ID so that the user can add an Author and doesnt have to write in the ID themself, as that would be pretty unsafe to do (for example if an author have ID=1 and they try to add another author with the same ID number it would create an error.)
Edit: Adding SQLServer table creation code
CREATE TABLE [dbo].[Author]
(
[AuthorId] INT NOT NULL IDENTITY(1,1),
[Name] NVARCHAR (50) NOT NULL,
[Nationality] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([AuthorId] ASC)
);