Escali License control 1
RegionService.cs
Gå til dokumentasjonen til denne filen.
3using Microsoft.EntityFrameworkCore;
4
6{
7
11public class RegionService
12{
13
14 public readonly DataContext _db;
15
17 {
18 _db = db;
19 }
20
25 public async Task<List<Region>> GetAllRegions()
26 {
27 var res = await _db.Regions.ToListAsync();
28 return res;
29 }
30
37 public async Task<Region> GetRegionById(int id)
38 {
39 var res = await _db.Regions.FindAsync(id);
40 return res;
41 }
42
50 public async Task<Region> AddRegion(Region region)
51 {
52 if (_db.Regions.Any(r => r.Area == region.Area && r.Country == region.Country))
53 throw new InvalidOperationException($"Region name already exist");
54
55 var res = _db.Regions.Add(region);
56 await _db.SaveChangesAsync();
57 return res.Entity;
58 }
59
67 public async Task<Region> UpdateRegion(Region region)
68 {
69 if (_db.Regions.Any(r => r.Area == region.Area && r.Country != region.Country))
70 throw new InvalidOperationException($"update region error");
71
72 var res = _db.Regions.Update(region);
73 await _db.SaveChangesAsync();
74 return res.Entity;
75 }
76
77
78
79}
80
81}
RegionService class inserts and updates Region in the Database
async Task< Region > UpdateRegion(Region region)
Updates changes on a Region in the database
async Task< List< Region > > GetAllRegions()
Read all Regions from database
async Task< Region > GetRegionById(int id)
Read one Region with id from database
async Task< Region > AddRegion(Region region)
Adds a Region to the database