-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrainService.cs
More file actions
50 lines (40 loc) · 1.5 KB
/
TrainService.cs
File metadata and controls
50 lines (40 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using TrainAPI.Entities;
using TrainAPI.Model;
namespace TrainAPI
{
public class TrainService
{
private readonly IMongoCollection<Train> _trainCollection;
public TrainService(IOptions<TrainDbSettings> settings)
{
var mongoClient = new MongoClient(
settings.Value.ConnectionString);
var mongoDatabase = mongoClient.GetDatabase(
settings.Value.DatabaseName);
_trainCollection = mongoDatabase.GetCollection<Train>(
settings.Value.CollectionName);
}
public async Task<List<Train>> GetAsync() =>
await _trainCollection.Find(_ => true).ToListAsync();
public async Task<Train?> GetAsync(string id) =>
await _trainCollection.Find(x => x.Id == id).FirstOrDefaultAsync();
public async Task<Train> CreateAsync(TrainModel model)
{
var train = new Train()
{
Id = Guid.NewGuid().ToString(),
From = model.From,
To = model.To,
Date = model.Date,
};
await _trainCollection.InsertOneAsync(train);
return train;
}
public async Task UpdateAsync(Train model) =>
await _trainCollection.ReplaceOneAsync(x => x.Id == model.Id, model);
public async Task RemoveAsync(string id) =>
await _trainCollection.DeleteOneAsync(x => x.Id == id);
}
}