Hello,
I have developped a .Net Core 5.0 Web API and I pass the following json as [FromBody] parameters to update the book in database and it updates successfully.
id=> 1
[FromBody] parameters=>
{
"Title": "Sun",
"Description": "store sun",
"Genre": "man",
"CoverUrl": "www.CCC.fr"
}
But when I want to only update "Title", "Description", "CoverUrl" and pass the following json as [FromBody] parameters. After the updates, I found the data is not correct in the database because the other information "Genre" is set to ""...(In the database, Id=>1, "Title"=>"Sun to update", "Description"=>"","Genre"=>"", "CoverUrl"=>"")
id=> 1
[FromBody] parameters=>
{
"Title": "Sun to update"
"Description": null,
"CoverUrl": ""
}
Is there a way to only update "Title" "Description", "CoverUrl" without changing the other information "Genre" via [FromBody], thanks in advance.
This is the BooksController.cs=>
namespace books.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
public BooksService _booksService;
public BooksController(BooksService booksService)
{
_booksService = booksService;
}
[HttpPut("{id}")]
public IActionResult UpdateBookById(int id, [FromBody]Book book)
{
var updatedBook = _booksService.UpdateBookById(id, book);
return Ok(updatedBook);
}
}
}
This is the book.cs=>
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Genre { get; set; }
public string CoverUrl { get; set; }
}
This is the BooksService.cs=>
public class BooksService
{
private AppDbContext _context;
public BooksService(AppDbContext context)
{
_context = context;
}
public Book UpdateBookById(int bookId, Book book)
{
var _book = _context.Books.FirstOrDefault(n => n.Id == bookId);
if(_book != null)
{
_book.Title = book.Title;
_book.Description = book.Description;
_book.Genre = book.Genre;
_book.CoverUrl = book.CoverUrl;
_context.SaveChanges();
}
return _book;
}
}