Using SQL-Server the following first checks if there are rows (there are actually simpler ways to do this but this here has less of an impact on the server), if not return 1 else return the last id.
Note on the table name, this should really be a parameter to the SqlCommand object which is easy enough to do.
public class SqlOperations
{
/// <summary>
/// SQL-Server name
/// </summary>
public static string Server { get; set; }
/// <summary>
/// Database in Server
/// </summary>
public static string Database { get; set; }
public static int GetLastIdentifier()
{
using var cn = new SqlConnection($"Server={Server};Database={Database};Integrated Security=true");
var selectStatement =
"SELECT SUM(row_count) AS rows FROM sys.dm_db_partition_stats " +
"WHERE object_id = OBJECT_ID('Customers') AND index_id < 2 " +
"GROUP BY OBJECT_NAME(object_id);";
using var cmd = new SqlCommand(selectStatement, cn);
cn.Open();
var identifier = Convert.ToInt64(cmd.ExecuteScalar());
if (identifier == 0)
{
return 1;
}
else
{
cmd.CommandText = "SELECT IDENT_CURRENT('Customers')";
return (int) Convert.ToInt64(cmd.ExecuteScalar());
}
}
}
Example
SqlOperations.Server = ".\\SQLEXPRESS";
SqlOperations.Database = "NorthWind2020";
var id = SqlOperations.GetLastIdentifier().ToString();