11using DotNetWebAPI_InMemoryDatabase . Data ;
22using DotNetWebAPI_InMemoryDatabase . Models ;
3- using Microsoft . AspNetCore . Http . HttpResults ;
4- using Microsoft . AspNetCore . Mvc ;
3+ using Microsoft . EntityFrameworkCore ;
4+ using Microsoft . Extensions . Logging ;
55
66namespace DotNetWebAPI_InMemoryDatabase . Services
77{
88 public class BookServices : IBooks
99 {
1010 private readonly BookContext _context ;
11+ private readonly ILogger < BookServices > _logger ;
1112
12-
13- public BookServices ( BookContext context )
13+ public BookServices ( BookContext context , ILogger < BookServices > logger )
1414 {
1515 _context = context ;
16+ _logger = logger ;
1617 }
1718
1819 public void AddBook ( Book book )
1920 {
21+ _logger . LogInformation ( "Attempting to add a new book with Title: {Title}" , book . Title ) ;
2022
2123 _context . Books . Add ( book ) ;
2224 _context . SaveChanges ( ) ;
2325
26+ _logger . LogInformation ( "Book added successfully with Id: {Id}" , book . Id ) ;
2427 }
2528
2629 public void DeleteBook ( int bookid )
2730 {
31+ _logger . LogInformation ( "Attempting to delete book with Id: {Id}" , bookid ) ;
32+
2833 var book = _context . Books . FirstOrDefault ( x => x . Id == bookid ) ;
34+
2935 if ( book != null )
3036 {
3137 _context . Books . Remove ( book ) ;
3238 _context . SaveChanges ( ) ;
33- }
3439
40+ _logger . LogInformation ( "Book deleted successfully with Id: {Id}" , bookid ) ;
41+ }
42+ else
43+ {
44+ _logger . LogWarning ( "Delete failed. Book not found with Id: {Id}" , bookid ) ;
45+ }
3546 }
3647
3748 public IEnumerable < Book > GetAllBooks ( )
3849 {
50+ _logger . LogInformation ( "Fetching all books" ) ;
3951
52+ var books = _context . Books . AsNoTracking ( ) . ToList ( ) ;
4053
41- IEnumerable < Book > books = _context . Books ;
42- if ( books == null )
43- {
44- return null ;
45- }
46- return books ;
47-
54+ _logger . LogInformation ( "Total books retrieved: {Count}" , books . Count ) ;
4855
56+ return books ;
4957 }
5058
5159 public Book GetBook ( int bookid )
5260 {
53- Book book = _context . Books . FirstOrDefault ( book => book . Id == bookid ) ;
61+ _logger . LogInformation ( "Fetching book with Id: {Id}" , bookid ) ;
62+
63+ var book = _context . Books . FirstOrDefault ( book => book . Id == bookid ) ;
64+
5465 if ( book != null )
5566 {
67+ _logger . LogInformation ( "Book found with Id: {Id}" , bookid ) ;
5668 return book ;
57- } return null ;
69+ }
70+
71+ _logger . LogWarning ( "Book not found with Id: {Id}" , bookid ) ;
72+ return null ;
5873 }
5974
6075 public void UpdateBook ( Book book )
6176 {
77+ _logger . LogInformation ( "Attempting to update book with Id: {Id}" , book . Id ) ;
78+
6279 _context . Update ( book ) ;
63- _context . SaveChanges ( true ) ;
80+ _context . SaveChanges ( ) ;
81+
82+ _logger . LogInformation ( "Book updated successfully with Id: {Id}" , book . Id ) ;
6483 }
6584 }
66- }
85+ }
0 commit comments