1 |
fad0afca
|
Dominik Chlouba
|
using Microsoft.EntityFrameworkCore;
|
2 |
|
|
using Microsoft.Extensions.DependencyInjection;
|
3 |
|
|
using System;
|
4 |
|
|
using System.Linq;
|
5 |
|
|
using System.Threading;
|
6 |
|
|
|
7 |
|
|
namespace Leuze.Tests.Configuration
|
8 |
|
|
{
|
9 |
|
|
/// <summary>
|
10 |
|
|
///
|
11 |
|
|
/// </summary>
|
12 |
|
|
public class TestWithDatabase : IDisposable
|
13 |
|
|
{
|
14 |
|
|
/// <summary>
|
15 |
|
|
///
|
16 |
|
|
/// </summary>
|
17 |
|
|
protected DatabaseInMemoryFixture DatabaseFixture { get; private set; } = null!;
|
18 |
|
|
|
19 |
|
|
/// <summary>
|
20 |
|
|
///
|
21 |
|
|
/// </summary>
|
22 |
|
|
protected static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
|
23 |
|
|
|
24 |
|
|
/// <summary>
|
25 |
|
|
///
|
26 |
|
|
/// </summary>
|
27 |
|
|
/// <param name="services"></param>
|
28 |
|
|
public void Initialize(ServiceCollection services) => DatabaseFixture = new(services);
|
29 |
|
|
|
30 |
|
|
/// <summary>
|
31 |
|
|
///
|
32 |
|
|
/// </summary>
|
33 |
|
|
public void Dispose() => CleanTrackedEntities();
|
34 |
|
|
|
35 |
|
|
/// <summary>
|
36 |
|
|
///
|
37 |
|
|
/// </summary>
|
38 |
|
|
protected void CleanTrackedEntities()
|
39 |
|
|
{
|
40 |
|
|
var changedEntriesCopy = DatabaseFixture.Storage.ChangeTracker.Entries()
|
41 |
|
|
.Where(e => e.State == EntityState.Added ||
|
42 |
|
|
e.State == EntityState.Modified ||
|
43 |
|
|
e.State == EntityState.Deleted)
|
44 |
|
|
.ToList();
|
45 |
|
|
foreach (var entity in changedEntriesCopy)
|
46 |
|
|
{
|
47 |
|
|
DatabaseFixture.Storage.Entry(entity.Entity).State = EntityState.Detached;
|
48 |
|
|
}
|
49 |
|
|
}
|
50 |
|
|
}
|
51 |
|
|
}
|