1- using System . Text . Json ;
2- using Microsoft . AspNetCore . Hosting ;
1+ using Microsoft . EntityFrameworkCore ;
2+ using MoveIT . Data ;
33using MoveIT . Models ;
44
55namespace MoveIT . Services ;
66
77public class InventoryService
88{
9- private readonly string _filePath ;
10- private List < MovingItem > _items ;
11- private static readonly JsonSerializerOptions _jsonOptions = new ( ) { WriteIndented = true } ;
9+ private readonly IDbContextFactory < MoveItDbContext > _dbFactory ;
10+ private readonly List < MovingItem > _items ;
1211
13- public InventoryService ( IWebHostEnvironment env )
12+ public InventoryService ( IDbContextFactory < MoveItDbContext > dbFactory )
1413 {
15- _filePath = Path . Combine ( env . ContentRootPath , "inventory.json" ) ;
16- _items = Load ( ) ;
14+ _dbFactory = dbFactory ;
15+ using var db = _dbFactory . CreateDbContext ( ) ;
16+ _items = db . Items . AsNoTracking ( ) . ToList ( ) ;
1717 }
1818
1919 public IReadOnlyList < MovingItem > Items => _items . AsReadOnly ( ) ;
@@ -25,40 +25,31 @@ public InventoryService(IWebHostEnvironment env)
2525
2626 public void Add ( MovingItem item )
2727 {
28+ using var db = _dbFactory . CreateDbContext ( ) ;
29+ db . Items . Add ( item ) ;
30+ db . SaveChanges ( ) ;
2831 _items . Add ( item ) ;
29- Save ( ) ;
3032 }
3133
3234 public void Update ( MovingItem updated )
3335 {
36+ using var db = _dbFactory . CreateDbContext ( ) ;
37+ var existing = db . Items . Find ( updated . Id ) ;
38+ if ( existing is null ) return ;
39+ db . Entry ( existing ) . CurrentValues . SetValues ( updated ) ;
40+ db . SaveChanges ( ) ;
41+
3442 var idx = _items . FindIndex ( x => x . Id == updated . Id ) ;
35- if ( idx >= 0 )
36- {
37- _items [ idx ] = updated ;
38- Save ( ) ;
39- }
43+ if ( idx >= 0 ) _items [ idx ] = updated ;
4044 }
4145
4246 public void Remove ( Guid id )
4347 {
48+ using var db = _dbFactory . CreateDbContext ( ) ;
49+ var existing = db . Items . Find ( id ) ;
50+ if ( existing is null ) return ;
51+ db . Items . Remove ( existing ) ;
52+ db . SaveChanges ( ) ;
4453 _items . RemoveAll ( x => x . Id == id ) ;
45- Save ( ) ;
4654 }
47-
48- private List < MovingItem > Load ( )
49- {
50- if ( ! File . Exists ( _filePath ) ) return [ ] ;
51- try
52- {
53- var json = File . ReadAllText ( _filePath ) ;
54- return JsonSerializer . Deserialize < List < MovingItem > > ( json , _jsonOptions ) ?? [ ] ;
55- }
56- catch
57- {
58- return [ ] ;
59- }
60- }
61-
62- private void Save ( ) =>
63- File . WriteAllText ( _filePath , JsonSerializer . Serialize ( _items , _jsonOptions ) ) ;
6455}
0 commit comments