Skip to content

Commit d0e8b05

Browse files
author
RahulMule
committed
Added other CRUD Operations
1 parent a406a6c commit d0e8b05

3 files changed

Lines changed: 49 additions & 0 deletions

File tree

DotNetWebAPI_InMemoryDatabase/Controllers/BooksController.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,28 @@ public IActionResult AddBook(Book book)
2626
_books.AddBook(book);
2727
return Ok();
2828
}
29+
[HttpDelete]
30+
public IActionResult DeleteBook(int id)
31+
{
32+
_books.DeleteBook(id);
33+
return Ok();
34+
}
35+
[HttpPut]
36+
public IActionResult PutBook(Book book)
37+
{
38+
if (ModelState.IsValid) {
39+
_books.UpdateBook(book);
40+
return Ok();
41+
} return BadRequest();
42+
}
43+
[HttpGet("{id}")]
44+
public IActionResult GetBook(int id)
45+
{
46+
Book book = _books.GetBook(id);
2947

48+
return Ok(book);
49+
}
50+
51+
3052
}
3153
}

DotNetWebAPI_InMemoryDatabase/Services/BookServices.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ public void AddBook(Book book)
2323

2424
}
2525

26+
public void DeleteBook(int bookid)
27+
{
28+
var book = _context.Books.FirstOrDefault(x => x.Id == bookid);
29+
if (book != null)
30+
{
31+
_context.Books.Remove(book);
32+
_context.SaveChanges();
33+
}
34+
35+
}
2636

2737
public IEnumerable<Book> GetAllBooks()
2838
{
@@ -38,5 +48,19 @@ public IEnumerable<Book> GetAllBooks()
3848

3949
}
4050

51+
public Book GetBook(int bookid)
52+
{
53+
Book book = _context.Books.FirstOrDefault(book => book.Id == bookid);
54+
if (book != null)
55+
{
56+
return book;
57+
}return null;
58+
}
59+
60+
public void UpdateBook(Book book)
61+
{
62+
_context.Update(book);
63+
_context.SaveChanges(true);
64+
}
4165
}
4266
}

DotNetWebAPI_InMemoryDatabase/Services/IBooks.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,8 @@ public interface IBooks
77
{
88
public IEnumerable<Book> GetAllBooks();
99
public void AddBook(Book book);
10+
public void DeleteBook(int bookid);
11+
public void UpdateBook(Book book);
12+
public Book GetBook(int bookid);
1013
}
1114
}

0 commit comments

Comments
 (0)