-
Notifications
You must be signed in to change notification settings - Fork 295
/
AppDbContext.cs
67 lines (56 loc) · 1.87 KB
/
AppDbContext.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using ClinicManagement.Core.Aggregates;
using MediatR;
using Microsoft.EntityFrameworkCore;
using PluralsightDdd.SharedKernel;
namespace ClinicManagement.Infrastructure.Data
{
public class AppDbContext : DbContext
{
private readonly IMediator _mediator;
public AppDbContext(DbContextOptions<AppDbContext> options, IMediator mediator)
: base(options)
{
_mediator = mediator;
}
public DbSet<Client> Clients { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<Room> Rooms { get; set; }
public DbSet<Patient> Patients { get; set; }
public DbSet<AppointmentType> AppointmentTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
int result = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// ignore events if no dispatcher provided
if (_mediator == null) return result;
var entitiesWithEvents = ChangeTracker
.Entries()
.Select(e => e.Entity as BaseEntity<Guid>)
.Where(e => e?.Events != null && e.Events.Any())
.ToArray();
foreach (var entity in entitiesWithEvents)
{
var events = entity.Events.ToArray();
entity.Events.Clear();
foreach (var domainEvent in events)
{
await _mediator.Publish(domainEvent).ConfigureAwait(false);
}
}
return result;
}
public override int SaveChanges()
{
return SaveChangesAsync().GetAwaiter().GetResult();
}
}
}