-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAppDbContext.cs
More file actions
323 lines (274 loc) · 14.1 KB
/
Copy pathAppDbContext.cs
File metadata and controls
323 lines (274 loc) · 14.1 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.Extensions.Caching.Memory;
using PrismaApi.Domain.Constants;
using PrismaApi.Domain.Entities;
using PrismaApi.Domain.Extensions;
using PrismaApi.Domain.Interfaces;
using PrismaApi.Infrastructure.DiscreteTables;
namespace PrismaApi.Infrastructure.Context;
public partial class AppDbContext : DbContext
{
private readonly IMemoryCache _cache;
public readonly AppDbContextOptions AppOptions;
public AppDbContext(DbContextOptions<AppDbContext> options, IMemoryCache cache, AppDbContextOptions appOptions) : base(options)
{
_cache = cache;
AppOptions = appOptions;
}
public DiscreteTableSessionInfo DiscreteTableSessionInfo { get; } = new();
public bool IsDiscreteTableEventDisabled { get; set; }
public DbSet<Project> Projects => Set<Project>();
public DbSet<Issue> Issues => Set<Issue>();
public DbSet<Node> Nodes => Set<Node>();
public DbSet<NodeStyle> NodeStyles => Set<NodeStyle>();
public DbSet<Edge> Edges => Set<Edge>();
public DbSet<Decision> Decisions => Set<Decision>();
public DbSet<Option> Options => Set<Option>();
public DbSet<Outcome> Outcomes => Set<Outcome>();
public DbSet<Uncertainty> Uncertainties => Set<Uncertainty>();
public DbSet<Utility> Utilities => Set<Utility>();
public DbSet<ValueMetric> ValueMetrics => Set<ValueMetric>();
public DbSet<DiscreteProbability> DiscreteProbabilities => Set<DiscreteProbability>();
public DbSet<DiscreteProbabilityParentOutcome> DiscreteProbabilityParentOutcomes => Set<DiscreteProbabilityParentOutcome>();
public DbSet<DiscreteProbabilityParentOption> DiscreteProbabilityParentOptions => Set<DiscreteProbabilityParentOption>();
public DbSet<DiscreteUtility> DiscreteUtilities => Set<DiscreteUtility>();
public DbSet<DiscreteUtilityParentOutcome> DiscreteUtilityParentOutcomes => Set<DiscreteUtilityParentOutcome>();
public DbSet<DiscreteUtilityParentOption> DiscreteUtilityParentOptions => Set<DiscreteUtilityParentOption>();
public DbSet<Strategy> Strategies => Set<Strategy>();
public DbSet<StrategyOption> StrategyOptions => Set<StrategyOption>();
public DbSet<Objective> Objectives => Set<Objective>();
public DbSet<ProjectRole> ProjectRoles => Set<ProjectRole>();
public DbSet<User> Users => Set<User>();
public DbSet<Assessment> Assessments => Set<Assessment>();
public DbSet<DecisionQualityAssessment> DecisionQualityAssessments => Set<DecisionQualityAssessment>();
public DbSet<BoardNode> BoardNodes => Set<BoardNode>();
public DbSet<BoardSheet> BoardSheets => Set<BoardSheet>();
public DbSet<RestrictionTable> RestrictionTables => Set<RestrictionTable>();
public DbSet<RestrictionEntry> RestrictionEntries => Set<RestrictionEntry>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
Project.OnModelConfiguring(modelBuilder);
Issue.OnModelConfiguring(modelBuilder);
Node.OnModelConfiguring(modelBuilder);
NodeStyle.OnModelConfiguring(modelBuilder);
Edge.OnModelConfiguring(modelBuilder);
Decision.OnModelConfiguring(modelBuilder);
Option.OnModelConfiguring(modelBuilder);
Outcome.OnModelConfiguring(modelBuilder);
Uncertainty.OnModelConfiguring(modelBuilder);
Utility.OnModelConfiguring(modelBuilder);
DiscreteProbability.OnModelConfiguring(modelBuilder);
DiscreteProbabilityParentOutcome.OnModelConfiguring(modelBuilder);
DiscreteProbabilityParentOption.OnModelConfiguring(modelBuilder);
DiscreteUtility.OnModelConfiguring(modelBuilder);
DiscreteUtilityParentOutcome.OnModelConfiguring(modelBuilder);
DiscreteUtilityParentOption.OnModelConfiguring(modelBuilder);
ValueMetric.OnModelConfiguring(modelBuilder);
Strategy.OnModelConfiguring(modelBuilder);
StrategyOption.OnModelConfiguring(modelBuilder);
Objective.OnModelConfiguring(modelBuilder);
ProjectRole.OnModelConfiguring(modelBuilder);
User.OnModelConfiguring(modelBuilder);
Assessment.OnModelConfiguring(modelBuilder);
DecisionQualityAssessment.OnModelConfiguring(modelBuilder);
BoardNode.OnModelConfiguring(modelBuilder);
BoardSheet.OnModelConfiguring(modelBuilder);
RestrictionTable.OnModelConfiguring(modelBuilder);
RestrictionEntry.OnModelConfiguring(modelBuilder);
}
private IEnumerable<EntityEntry<T>> GetChangedEntries<T>() where T : class =>
ChangeTracker.Entries<T>()
.Where(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted);
public override int SaveChanges()
{
throw new InvalidOperationException("Use SaveChangesAsync instead.");
}
public async override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
UpdateTimestamps();
await EnforceMinimumProjectRoles(cancellationToken);
await OnNodeDeletedCleanupAsync(cancellationToken);
await OnOutcomeDeletedCleanupAsync(cancellationToken);
await OnOptionDeletedCleanupAsync(cancellationToken);
// invalidate before savechanges because save changes clears out the change tracker
await InvalidateCacheAsync();
return await base.SaveChangesAsync(cancellationToken);
}
public async Task<int> SaveChangesWhileDuplicatingAsync(CancellationToken cancellationToken = default)
{
// Alternitive design can be found at https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/events
// no need to invalidate cache here since the duplicated entities will have new ids
// and won't affect existing cache entries
return await base.SaveChangesAsync(cancellationToken);
}
private void UpdateTimestamps()
{
var entries = ChangeTracker.Entries<BaseEntity>()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);
foreach (var entry in entries)
{
if (entry.State == EntityState.Added)
{
var preserveCreatedTimestamp = entry.Entity is Outcome or Option;
if (!preserveCreatedTimestamp || entry.Entity.CreatedAt == default)
{
entry.Entity.CreatedAt = DateTimeOffset.UtcNow;
}
}
entry.Entity.UpdatedAt = DateTimeOffset.UtcNow;
}
}
private async Task EnforceMinimumProjectRoles(CancellationToken cancellationToken)
{
// get the roles that have been deleted or modified and group by the project id
// to make it easier to iterate over the projects
var affectedByProject = ChangeTracker
.Entries<ProjectRole>()
.Where(e => e.State == EntityState.Deleted || e.State == EntityState.Modified)
.GroupBy(e => e.Entity.ProjectId)
.ToDictionary(g => g.Key, g => g);
if (affectedByProject.Count == 0)
return;
foreach (var (projectId, roles) in affectedByProject)
{
var facilitatorRole = ProjectRoleType.Facilitator.ToString();
var facilitatorsBeingRemoved = roles.Count(role =>
role.State == EntityState.Deleted
? role.Entity.Role.IsFacilitator()
: role.OriginalValues.GetValue<string>(nameof(ProjectRole.Role)).IsFacilitator()
&& !role.CurrentValues.GetValue<string>(nameof(ProjectRole.Role)).IsFacilitator());
if (facilitatorsBeingRemoved == 0)
continue;
var currentFacilitatorCount = await ProjectRoles
.AsNoTracking()
.CountAsync(r => r.ProjectId == projectId &&
r.Role.ToLower() == ProjectRoleType.Facilitator.ToString().ToLower(),
cancellationToken);
if (currentFacilitatorCount - facilitatorsBeingRemoved <= 0)
throw new InvalidOperationException(ExceptionMessages.MinimumFacilitatorRequirement);
}
}
private async Task OnNodeDeletedCleanupAsync(CancellationToken cancellationToken = default)
{
var deletedNodeIds = GetDeletedEntityIds<Node>();
if (deletedNodeIds.Any())
{
// Delete tail edges that reference the deleted nodes
var tailEdgesToDelete = await Edges
.Where(e => deletedNodeIds.Contains(e.TailId) || deletedNodeIds.Contains(e.HeadId))
.ToListAsync(cancellationToken);
Edges.RemoveRange(tailEdgesToDelete);
}
}
private async Task OnOutcomeDeletedCleanupAsync(CancellationToken cancellationToken = default)
{
var deletedOutcomeIds = GetDeletedEntityIds<Outcome>();
if (deletedOutcomeIds.Any())
{
// Load the parent outcome relationships and the discrete probabilities they reference
var affectedProbParentOutcomes = await DiscreteProbabilityParentOutcomes
.AsSplitQuery()
.Where(po => deletedOutcomeIds.Contains(po.ParentOutcomeId))
.Include(po => po.DiscreteProbability)
.ThenInclude(dp => dp!.ParentOptions)
.Include(po => po.DiscreteProbability)
.ThenInclude(dp => dp!.ParentOutcomes)
.ToListAsync(cancellationToken);
var affectedProbs = affectedProbParentOutcomes
.Select(po => po.DiscreteProbability)
.Where(dp => dp != null)
.Distinct()
.Cast<DiscreteProbability>()
.ToList();
DiscreteProbabilities.RemoveRange(affectedProbs);
// Load the parent outcome relationships and the discrete utilities they reference
var affectedUtilParentOutcomes = await DiscreteUtilityParentOutcomes
.AsSplitQuery()
.Where(uo => deletedOutcomeIds.Contains(uo.ParentOutcomeId))
.Include(uo => uo.DiscreteUtility)
.ThenInclude(du => du!.ParentOptions)
.Include(uo => uo.DiscreteUtility)
.ThenInclude(du => du!.ParentOutcomes)
.ToListAsync(cancellationToken);
var affectedUtils = affectedUtilParentOutcomes
.Select(uo => uo.DiscreteUtility)
.Where(du => du != null)
.Distinct()
.Cast<DiscreteUtility>()
.ToList();
DiscreteUtilities.RemoveRange(affectedUtils);
var affectedRestrictionEntries = await RestrictionEntries
.Where(
re => (re.ParentOutcomeId != null && deletedOutcomeIds.Contains((Guid)re.ParentOutcomeId)) ||
(re.ChildOutcomeId != null && deletedOutcomeIds.Contains((Guid)re.ChildOutcomeId)))
.ToListAsync(cancellationToken);
RestrictionEntries.RemoveRange(affectedRestrictionEntries);
}
}
private async Task OnOptionDeletedCleanupAsync(CancellationToken cancellationToken = default)
{
var deletedOptionIds = GetDeletedEntityIds<Option>();
if (deletedOptionIds.Any())
{
var strategyOptionsToDelete = await StrategyOptions
.Where(e => deletedOptionIds.Contains(e.OptionId))
.ToListAsync();
StrategyOptions.RemoveRange(strategyOptionsToDelete);
// Load the parent option relationships and the discrete probabilities they reference
var affectedProbParentOptions = await DiscreteProbabilityParentOptions
.AsSplitQuery()
.Where(po => deletedOptionIds.Contains(po.ParentOptionId))
.Include(po => po.DiscreteProbability)
.ThenInclude(dp => dp!.ParentOptions)
.Include(po => po.DiscreteProbability)
.ThenInclude(dp => dp!.ParentOutcomes)
.ToListAsync(cancellationToken);
var affectedProbs = affectedProbParentOptions
.Select(po => po.DiscreteProbability)
.Where(dp => dp != null)
.Distinct()
.Cast<DiscreteProbability>()
.ToList();
DiscreteProbabilities.RemoveRange(affectedProbs);
DiscreteProbabilityParentOptions.RemoveRange(affectedProbParentOptions);
// Load the parent option relationships and the discrete utilities they reference
var affectedUtilParentOptions = await DiscreteUtilityParentOptions
.AsSplitQuery()
.Where(uo => deletedOptionIds.Contains(uo.ParentOptionId))
.Include(uo => uo.DiscreteUtility)
.ThenInclude(du => du!.ParentOptions)
.Include(uo => uo.DiscreteUtility)
.ThenInclude(du => du!.ParentOutcomes)
.ToListAsync(cancellationToken);
var affectedUtils = affectedUtilParentOptions
.Select(uo => uo.DiscreteUtility)
.Where(du => du != null)
.Distinct()
.Cast<DiscreteUtility>()
.ToList();
DiscreteUtilities.RemoveRange(affectedUtils);
DiscreteUtilityParentOptions.RemoveRange(affectedUtilParentOptions);
var affectedRestrictionEntries = await RestrictionEntries
.Where(
re => (re.ParentOptionId != null && deletedOptionIds.Contains((Guid)re.ParentOptionId)) ||
(re.ChildOptionId != null && deletedOptionIds.Contains((Guid)re.ChildOptionId)))
.ToListAsync(cancellationToken);
RestrictionEntries.RemoveRange(affectedRestrictionEntries);
}
}
private HashSet<Guid> GetDeletedEntityIds<TEntity>()
where TEntity : class, IBaseEntity<Guid>
{
return ChangeTracker.Entries<TEntity>()
.Where(e => e.State == EntityState.Deleted)
.Select(e => e.Entity.Id)
.ToHashSet();
}
public EntityEntry<IBaseEntity<Guid>> CreateEntryFromCollectionAsAdded(IBaseEntity<Guid> entity)
{
Entry(entity).State = EntityState.Added;
return base.Add(entity);
}
}