Thinker
Thinker

Reputation: 5356

ASP.Net core Web Api with EF Core Update entity howto

NOT A DUPLICATE: My Update() methods takes two arguements: id and modified entity, and answers provided to my question have different approach like CurrentValues which isn't covered in existing questions.

I am new to ASP.Net core development. I am building a simple API with MySql as database and with a Book model.

I have written my controller like following:

[Route("api/[controller]")]
    public class BooksController : Controller
    {
        private readonly IBookRepository _books;
        public BooksController(IBookRepository books)
        {
            _books = books;
        }

        [HttpGet("")]
        public IActionResult GetAllBooks()
        {
            try
            {
                List<Book> books = _books.GetAllBooks();
                return Ok(books);
            }
            catch(EntityNotFoundException<Book>)
            {
                return NotFound();
            }

        }

        [HttpGet("{id}")]
        public IActionResult GetBook(long id)
        {
            Book book = _books.GetBook(id);
            if (book == null)
            {
                return NotFound();
            }
            return Ok(book);
        }

        [HttpPost]
        public IActionResult CreateBook([FromBody] Book book)
        {
            if (ModelState.IsValid == false)
            {
                return BadRequest(ModelState);
            }

            Book createdBook = _books.CreateBook(book);
            if (createdBook == null)
            {
                return NotFound();
            }
            return CreatedAtAction(
                 nameof(GetBook), new { id = createdBook.Id }, createdBook);

        }

        [HttpPut("{id}")]
        public IActionResult UpdateBook(long id, [FromBody] Book book)
        {
            if (ModelState.IsValid == false)
            {
                return BadRequest(ModelState);
            }

            try
            {
                _books.UpdateBook(id, book);
                return Ok();
            }
            catch (EntityNotFoundException<Book>)
            {
                return NotFound();
            }
        }

        [HttpDelete("{id}")]
        public IActionResult DeleteBook(long id)
        {
            _books.DeleteBook(id);
            return Ok();
        }
    } 

And Repository as following:

public class BookRepository: IBookRepository
    {
        private readonly WebAPIDataContext _db;

        public BookRepository(WebAPIDataContext db) {
            _db = db;
        }

        public Book CreateBook(Book book) {
            _db.Books.Add(book);
            _db.SaveChanges();
            return book;
        }

        public void DeleteBook(long id)
        {
            Book book = GetBook(id);
            if (book != null) {
                _db.Books.Remove(book);
                _db.SaveChanges();
            }
        }

        public List<Book> GetAllBooks()
        {
            return _db.Books.AsNoTracking().ToList();
        }

        public Book GetBook(long id)
        {
            return _db.Books.FirstOrDefault(o => o.Id == id);
        }

        public void UpdateBook(long id, Book book)
        {


        }
    }

    public interface IBookRepository
    {
        List<Book> GetAllBooks();
        Book GetBook(long id);
        Book CreateBook(Book book);
        void UpdateBook(long id, Book book);
        void DeleteBook(long id);
    }

I am not sure how can I write the UpdateBook method in my Repo class. Can someone please help me with that? All the tutorial I saw were using single id parameter to UpdateBook() method, I am basically posting a json object as well along with entity id.

Upvotes: 2

Views: 8544

Answers (3)

cpr43
cpr43

Reputation: 3112

Try this

  public void UpdateBook(long id, Book book)
  {  
     var originalBook=  _db.Books.FirstOrDefault(o => o.Id == id);
     _db.Entry(originalBook).CurrentValues.SetValues(book);
     _db.SaveChanges();
  }

Kindly note that you have to use EFcore version 1.1 for this to work

Upvotes: 8

Andrii Litvinov
Andrii Litvinov

Reputation: 13182

I think Update method should do what you want. High-level idea is to attach entity and set its state to modified which is exactly what Update method does.

// Make sure that Book id is set correctly.
book.Id = id;
_db.Books.Update(book);
_db.SaveChanges();

Upvotes: 1

syned
syned

Reputation: 2321

The simplest way, you just load book from the database. Update fields and save changes to the database.

Book existingBook = GetBook(id);
existingBook.Title = book.Title;
// other properties
_db.SaveChanges();

Upvotes: 1

Related Questions