Escali License control 1
CurrencyService.cs
Gå til dokumentasjonen til denne filen.
3using Microsoft.EntityFrameworkCore;
4
6{
7
11public class CurrencyService
12{
13
14 private readonly DataContext _db;
15
17 {
18 _db = db;
19 }
20
25 public async Task<List<Currency>> GetAllCurrencies()
26 {
27 var res = await _db.Currencies.ToListAsync();
28 return res;
29 }
30
37 public async Task<Currency> GetCurrencyById(int id)
38 {
39 var res = await _db.Currencies.FindAsync(id);
40 return res;
41 }
42
49 public async Task<Currency> GetCurrencyByName(string name)
50 {
51 try
52 {
53 return await (from c in _db.Currencies
54 where c.CurrencyName == name
55 select c).FirstAsync();
56 }
57 catch (InvalidOperationException e)
58 {
59 return null;
60 }
61 }
62
69 public async Task<Currency> AddCurrency(Currency currency)
70 {
71 currency.CurrencyName = currency.CurrencyName.ToUpper();
72
73 if (_db.Currencies.Any(c => c.CurrencyName == currency.CurrencyName))
74 throw new InvalidOperationException($"Unique name violation.");
75
76 var res = _db.Currencies.Add(currency);
77 await _db.SaveChangesAsync();
78 return res.Entity;
79 }
80
88 public async Task<Currency> UpdateCurrency(Currency currency)
89 {
90 currency.CurrencyName = currency.CurrencyName.ToUpper();
91
92 if (_db.Currencies.Any(c => c.CurrencyName == currency.CurrencyName && c.CurrencySeq != currency.CurrencySeq))
93 throw new InvalidOperationException($"Unique name violation.");
94
95 var res = _db.Currencies.Update(currency);
96 await _db.SaveChangesAsync();
97 return res.Entity;
98 }
99
106 public async Task DeleteCurrency(int id)
107 {
108 var currency = await _db.Currencies.FindAsync(id);
109 if (currency == null) throw new NullReferenceException($"Currency with id {id} doesn't exist.");
110 _db.Currencies.Remove(currency);
111 }
112
113 }
114}
CurrencyService class inserts and updates Currency in the Database
async Task< Currency > UpdateCurrency(Currency currency)
Updates changes on a Currency in the database
async Task DeleteCurrency(int id)
Deletes a currency with id in the database
async Task< List< Currency > > GetAllCurrencies()
Read all Currencies from database
async Task< Currency > GetCurrencyById(int id)
Read one Currency with id from database
async Task< Currency > GetCurrencyByName(string name)
Read one Currency with name from database
async Task< Currency > AddCurrency(Currency currency)
Adds a Currency to the database