-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMongoDbContextShim.cs
38 lines (32 loc) · 1.2 KB
/
MongoDbContextShim.cs
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
using JsonApiDotNetCore.MongoDb.Resources;
using MongoDB.Driver;
namespace TestBuildingBlocks;
/// <summary>
/// Provides an Entity Framework Core DbContext-like abstraction that translates to MongoDB calls. This makes it easier to keep tests in sync with the
/// main repository.
/// </summary>
public abstract class MongoDbContextShim(IMongoDatabase database)
{
private readonly IMongoDatabase _database = database;
private readonly List<MongoDbSetShim> _dbSetShims = [];
protected MongoDbSetShim<TEntity> Set<TEntity>()
where TEntity : IMongoIdentifiable
{
IMongoCollection<TEntity> collection = _database.GetCollection<TEntity>(typeof(TEntity).Name);
var dbSetShim = new MongoDbSetShim<TEntity>(collection);
_dbSetShims.Add(dbSetShim);
return dbSetShim;
}
public async Task ClearTableAsync<TEntity>()
where TEntity : IMongoIdentifiable
{
await _database.DropCollectionAsync(typeof(TEntity).Name);
}
public async Task SaveChangesAsync(CancellationToken cancellation = default)
{
foreach (MongoDbSetShim dbSetShim in _dbSetShims)
{
await dbSetShim.PersistAsync(cancellation);
}
}
}