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

asp.net-core asp.net-core-mvc entity-framework-core

Question

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.

1
2
3/17/2017 9:15:03 AM

Popular Answer

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

8
3/17/2017 5:11:58 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow