Hello, I am doing a CRUD and the problem I have is that when I am going to update a single field through the method PUT
, I use the same model that I have for the method . POST
This model has validations and when invoking the method PUT
. it does not allow me because the other fields have validations and must go there
Model
public class BookShelfLine
{
public int Id { get; set; }
[Range(1, 10, ErrorMessage = "Rango permitido 1-10")]
public int Bookid { get; set; }
[Range(1, 10, ErrorMessage = "Rango permitido 1-10")]
public int Shelfid { get; set; }
[Range(1, 50, ErrorMessage = "Rango permitido 1-50")]
public int Avaliable { get; set; }
}
Controller
[Route("BookShelfLineInsert")]
[HttpPost]
public IActionResult BookShelfLineInsert(BookShelfLine bksl)
{
var MSJ = string.Empty;
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
string qry = @"INSERT INTO BookShelfLine (Bookid, Shelfid, Avaliable)
VALUES (@Bookid, @Shelfid, @Avaliable)";
string conexion = _config.GetConnectionString("BibliotecaString");
NpgsqlDataReader reader;
using (NpgsqlConnection con = new NpgsqlConnection(conexion))
{
con.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(qry, con))
{
cmd.Parameters.AddWithValue("@Bookid", bksl.Bookid);
cmd.Parameters.AddWithValue("@Shelfid", bksl.Shelfid);
cmd.Parameters.AddWithValue("@Avaliable", bksl.Avaliable);
reader = cmd.ExecuteReader();
MSJ = (reader.RecordsAffected > 0) ? "ROWS AFFECTED" : "NO ROWS AFFECTED";
}
con.Close();
}
}
catch (Exception ex)
{
MSJ = ex.Message + " " + ex.StackTrace;
}
return new JsonResult(MSJ);
}
[HttpPut("{id}")]
public IActionResult BookShelfLineUpdate(int id, BookShelfLine bSL)
{
var MSJ = string.Empty;
try
{
string qry = @"UPDATE BookShelfLine SET shelfid = @shelfid WHERE id = " + id +" ";
string conexion = _config.GetConnectionString("BibliotecaString");
NpgsqlDataReader reader;
using (NpgsqlConnection con = new NpgsqlConnection(conexion))
{
con.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(qry, con))
{
cmd.Parameters.AddWithValue("@Shelfid", bSL.Shelfid);
reader = cmd.ExecuteReader();
MSJ = (reader.RecordsAffected > 0) ? "ROWS AFFECTED" : "NO ROWS AFFECTED";
}
con.Close();
}
}
catch (Exception ex)
{
MSJ = ex.Message + " " + ex.StackTrace;
}
return new JsonResult(MSJ);
}
Using Postman gives me the following.
The easiest solution would be to create another model with that field but it is not the solution I am looking for.
Attentive to your comments
It really shouldn't be done that way, but if you want to continue using the same model, what you can do is add default values to the properties, so that they pass validation in the Put method.