I'm trying to create a comment system in a personal project and the following problem arose, when wanting to generate a new comment I do not recognize the Id of the comment and the ExecuteScalar
returns me as null
the Id, the idea is that when you generate a new comment the Id is increased.
Next I leave the code that inserts the comment in the database. I use Visual Studio 2015 and SQL Server 2014
// Insertar un nuevo comentario
public int InsertarComentario(Comentarios comentarios)
{
// Conectarse a la base de datos
SqlConnection conexion = new SqlConnection(ConfigurationManager.AppSettings["TecnoInfoConnectionString"]);
// Conectarnos
conexion.Open();
// Ejecutar la consulta
// Creamos la sentencia
SqlCommand comando = conexion.CreateCommand();
comando.CommandText = "INSERT INTO Comentarios (Comentario, IdUsuario, IdArticulo) OUTPUT INSERTED.IdComentario VALUES (@Comentario, @IdUsuario, @IdArticulo)";
comando.Parameters.AddWithValue("@Comentario", comentarios.Comentario);
comando.Parameters.AddWithValue("@IdUsuario", comentarios.IdUsuario);
comando.Parameters.AddWithValue("@IdArticulo", comentarios.IdArticulo);
// Ejecutarla
int nuevoIdComentario = (int)comando.ExecuteScalar(); //devuelve la primer columna de la primer fila
comentarios.IdComentario = nuevoIdComentario;
// Cerrar la conexion
conexion.Close();
// Devuelve el Id del nuevo articulo
return nuevoIdComentario;
}
The specific error is the following:
"Unable to insert NULL value in column 'CommentId', table 'Tecno_Info.dbo.Reviews'. Column does not support NULL values INSERT error."