From 02801c1b83f8f6083da23d0dd62b7dff76642e9c Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 17:34:45 +0000 Subject: [PATCH 01/16] Use centralized package management --- Directory.Build.props | 38 ++++++++----------- Directory.Packages.props | 18 +++++++++ EntityFrameworkCore.Triggered.sln | 1 + ...yFrameworkCore.Triggered.Benchmarks.csproj | 4 +- samples/1 - HelloWorld/1 - HelloWorld.csproj | 6 ++- .../Triggers/StudentAssignRegistrationDate.cs | 4 +- .../2 - PrimarySchool.csproj | 9 +++-- .../StudentSignupToMandatoryCourses.cs | 4 +- .../3 - StudentManagerAspNetCore.csproj | 6 ++- .../Triggers/Courses/AutoSignupStudents.cs | 4 +- .../BlockRemovalWhenCourseIsMandatory.cs | 4 +- .../StudentCourses/SendWelcomingEmail.cs | 4 +- .../Students/AssignRegistrationDate.cs | 4 +- .../Students/SignupToMandatoryCourses.cs | 4 +- .../Traits/Audited/CreateAuditRecord.cs | 4 +- .../Traits/SoftDelete/EnsureSoftDelete.cs | 4 +- .../4 - BlazorTests/4 - BlazorTests.csproj | 7 +++- .../Triggers/Counts/PublishCountAddedEvent.cs | 4 +- .../Triggers/Counts/SetCreatedOn.cs | 4 +- src/Directory.Build.props | 2 +- .../EntityFrameworkCore.Triggered.csproj | 2 +- ...workCore.Triggered.Extensions.Tests.csproj | 28 ++++++-------- ...workCore.Triggered.IntegrationTests.csproj | 24 ++++++------ ...EntityFrameworkCore.Triggered.Tests.csproj | 37 +++++++++--------- ...rkCore.Triggered.Transactions.Tests.csproj | 28 +++++++------- 25 files changed, 126 insertions(+), 128 deletions(-) create mode 100644 Directory.Packages.props diff --git a/Directory.Build.props b/Directory.Build.props index 689cf75..5ba6f62 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,31 +1,23 @@ - true - 9.0 - enable - true - Debug;Release - README.md - - - - Triggers for EF Core. Respond to changes in your ApplicationDbContext before and after they are committed to the database - Git - https://github.com/koenbeuk/EntityFrameworkCore.Triggered - Koen Bekkenutte - EntityFramework;EFCore;Triggers;SQLServer;SqlLite;CosmosDb;.NET Core;aspnetcore - https://github.com/koenbeuk/EntityFrameworkCore.Triggered + true + 9.0 + enable + true + README.md - + - 3 - 6.0.0 - 6.0.0 + Triggers for EF Core. Respond to changes in your ApplicationDbContext before and after they are committed to the database + Git + https://github.com/koenbeuk/EntityFrameworkCore.Triggered + Koen Bekkenutte + EntityFramework;EFCore;Triggers;SQLServer;SqlLite;CosmosDb;.NET Core;aspnetcore + https://github.com/koenbeuk/EntityFrameworkCore.Triggered - - - - + + + \ No newline at end of file diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..00b8396 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,18 @@ + + + true + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/EntityFrameworkCore.Triggered.sln b/EntityFrameworkCore.Triggered.sln index db3c390..64258d0 100644 --- a/EntityFrameworkCore.Triggered.sln +++ b/EntityFrameworkCore.Triggered.sln @@ -11,6 +11,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Solution Items", "_Solutio ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig Directory.Build.props = Directory.Build.props + Directory.Packages.props = Directory.Packages.props LICENSE.md = LICENSE.md README.md = README.md EndProjectSection diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj index 1dd0e35..95a47f2 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj @@ -12,8 +12,8 @@ Release - - + + diff --git a/samples/1 - HelloWorld/1 - HelloWorld.csproj b/samples/1 - HelloWorld/1 - HelloWorld.csproj index 3434bc4..9ac9676 100644 --- a/samples/1 - HelloWorld/1 - HelloWorld.csproj +++ b/samples/1 - HelloWorld/1 - HelloWorld.csproj @@ -8,8 +8,10 @@ - - + + + + diff --git a/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs b/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs index 804269b..417f1ea 100644 --- a/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs +++ b/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs @@ -7,14 +7,12 @@ namespace PrimarySchool.Triggers { public class StudentAssignRegistrationDate : IBeforeSaveTrigger { - public Task BeforeSave(ITriggerContext context, CancellationToken cancellationToken) + public void BeforeSave(ITriggerContext context) { if (context.ChangeType == ChangeType.Added) { context.Entity.RegistrationDate = DateTime.Today; } - - return Task.CompletedTask; } } } diff --git a/samples/2 - PrimarySchool/2 - PrimarySchool.csproj b/samples/2 - PrimarySchool/2 - PrimarySchool.csproj index ced6050..82980db 100644 --- a/samples/2 - PrimarySchool/2 - PrimarySchool.csproj +++ b/samples/2 - PrimarySchool/2 - PrimarySchool.csproj @@ -1,4 +1,4 @@ - + Exe @@ -8,8 +8,11 @@ - - + + + + + diff --git a/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs b/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs index 63bf1ca..5b6eb32 100644 --- a/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs +++ b/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs @@ -14,7 +14,7 @@ public StudentSignupToMandatoryCourses(ApplicationDbContext applicationContext) _applicationContext = applicationContext; } - public Task BeforeSave(ITriggerContext context, CancellationToken cancellationToken) + public void BeforeSave(ITriggerContext context) { var mandatoryCourses = _applicationContext.Courses .Where(x => x.IsMandatory) @@ -28,8 +28,6 @@ public Task BeforeSave(ITriggerContext context, CancellationToken cance _applicationContext.StudentCourses.Add(new StudentCourse { StudentId = context.Entity.Id, CourseId = mandatoryCourse.Id }); } } - - return Task.CompletedTask; } } } diff --git a/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj b/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj index 81a49c0..58a35a5 100644 --- a/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj +++ b/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj @@ -7,8 +7,10 @@ - - + + + + diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs index 0154d29..5352135 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs @@ -6,7 +6,7 @@ namespace StudentManager.Triggers.Courses { - public class AutoSignupStudents : IBeforeSaveTrigger + public class AutoSignupStudents : IBeforeSaveAsyncTrigger { readonly ApplicationDbContext _applicationContext; @@ -15,7 +15,7 @@ public AutoSignupStudents(ApplicationDbContext applicationContext) _applicationContext = applicationContext; } - public async Task BeforeSave(ITriggerContext context, CancellationToken cancellationToken) + public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) { if (context.Entity.IsMandatory) { diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs index 8013f31..673bd73 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs @@ -5,7 +5,7 @@ namespace StudentManager.Triggers.StudentCourses { - public class BlockRemovalWhenCourseIsMandatory : IBeforeSaveTrigger + public class BlockRemovalWhenCourseIsMandatory : IBeforeSaveAsyncTrigger { readonly ApplicationDbContext _applicationContext; @@ -14,7 +14,7 @@ public BlockRemovalWhenCourseIsMandatory(ApplicationDbContext applicationContext _applicationContext = applicationContext; } - public async Task BeforeSave(ITriggerContext context, CancellationToken cancellationToken) + public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) { if (context.ChangeType == ChangeType.Deleted) { diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs index d13c188..941291b 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs @@ -5,7 +5,7 @@ namespace StudentManager.Triggers.StudentCourses { - public class SendWelcomingEmail : IAfterSaveTrigger + public class SendWelcomingEmail : IAfterSaveAsyncTrigger { readonly ApplicationDbContext _applicationContext; readonly EmailService _emailService; @@ -16,7 +16,7 @@ public SendWelcomingEmail(ApplicationDbContext applicationContext, EmailService _emailService = emailService; } - public async Task AfterSave(ITriggerContext context, CancellationToken cancellationToken) + public async Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) { var student = await _applicationContext.Students.FindAsync(new object[] { context.Entity.StudentId }, cancellationToken); var course = await _applicationContext.Courses.FindAsync(new object[] { context.Entity.CourseId }, cancellationToken); diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs index 025d1d7..dd2f3ca 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs @@ -7,11 +7,9 @@ namespace StudentManager.Triggers.Students { public class AssignRegistrationDate : IBeforeSaveTrigger { - public Task BeforeSave(ITriggerContext context, CancellationToken cancellationToken) + public void BeforeSave(ITriggerContext context) { context.Entity.RegistrationDate = DateTime.Today; - - return Task.CompletedTask; } } } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs index ba20025..9baea35 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs @@ -6,7 +6,7 @@ namespace StudentManager.Triggers.Students { - public class SignupToMandatoryCourses : IBeforeSaveTrigger + public class SignupToMandatoryCourses : IBeforeSaveAsyncTrigger { readonly ApplicationDbContext _applicationContext; @@ -15,7 +15,7 @@ public SignupToMandatoryCourses(ApplicationDbContext applicationContext) _applicationContext = applicationContext; } - public async Task BeforeSave(ITriggerContext context, CancellationToken cancellationToken) + public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) { var mandatoryCourses = await _applicationContext.Courses .Where(x => x.IsMandatory) diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs index 9197864..4c2555b 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs @@ -17,7 +17,7 @@ public CreateAuditRecord(ApplicationDbContext applicationContext) _applicationContext = applicationContext; } - public Task BeforeSave(ITriggerContext context, CancellationToken cancellationToken) + public void BeforeSave(ITriggerContext context) { var recordBuilder = new StringBuilder(); @@ -37,8 +37,6 @@ public Task BeforeSave(ITriggerContext context, CancellationToken canc RecordDate = DateTimeOffset.Now, Record = recordBuilder.ToString() }); - - return Task.CompletedTask; } } } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs index d61e2a9..71482a7 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs @@ -15,15 +15,13 @@ public EnsureSoftDelete(ApplicationDbContext applicationContext) _applicationContext = applicationContext; } - public Task BeforeSave(ITriggerContext context, CancellationToken cancellationToken) + public void BeforeSave(ITriggerContext context) { if (context.ChangeType == ChangeType.Deleted) { context.Entity.DeletedOn = DateTimeOffset.Now; _applicationContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; } - - return Task.CompletedTask; } } } diff --git a/samples/4 - BlazorTests/4 - BlazorTests.csproj b/samples/4 - BlazorTests/4 - BlazorTests.csproj index 045a1d9..f05cc39 100644 --- a/samples/4 - BlazorTests/4 - BlazorTests.csproj +++ b/samples/4 - BlazorTests/4 - BlazorTests.csproj @@ -7,8 +7,11 @@ - - + + + + + diff --git a/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs b/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs index d79b85d..5b47829 100644 --- a/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs +++ b/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs @@ -13,14 +13,12 @@ public PublishCountAddedEvent(EventAggregator eventAggregator) _eventAggregator = eventAggregator; } - public Task AfterSave(ITriggerContext context, CancellationToken cancellationToken) + public void AfterSave(ITriggerContext context) { if (context.ChangeType == ChangeType.Added) { _eventAggregator.PublishCountAdded(context.Entity); } - - return Task.CompletedTask; } } } diff --git a/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs b/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs index 7c8f9b4..d0046a1 100644 --- a/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs +++ b/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs @@ -7,11 +7,9 @@ namespace BlazorTests.Triggers.Counts { public class SetCreatedOn : IBeforeSaveTrigger { - public Task BeforeSave(ITriggerContext context, CancellationToken cancellationToken) + public void BeforeSave(ITriggerContext context) { context.Entity.CreatedOn = DateTime.UtcNow; - - return Task.CompletedTask; } } } diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 06d4f16..0b76bee 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -34,7 +34,7 @@ - + \ No newline at end of file diff --git a/src/EntityFrameworkCore.Triggered/EntityFrameworkCore.Triggered.csproj b/src/EntityFrameworkCore.Triggered/EntityFrameworkCore.Triggered.csproj index 5f9df3b..909d546 100644 --- a/src/EntityFrameworkCore.Triggered/EntityFrameworkCore.Triggered.csproj +++ b/src/EntityFrameworkCore.Triggered/EntityFrameworkCore.Triggered.csproj @@ -1,7 +1,7 @@  - + diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj b/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj index a9d8e0a..b21a6a7 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj @@ -7,22 +7,18 @@ - - - - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj index 0ecc1d1..56ccc9e 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj @@ -7,18 +7,18 @@ - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj b/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj index 32e7a90..2dc9b07 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj +++ b/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj @@ -1,32 +1,29 @@  - net6.0 - false - disable + net6.0 + false + disable - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - + diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj b/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj index 93fe3cc..60bbddb 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj @@ -5,24 +5,22 @@ false disable - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + - + From ffbd5b29915b85ea78fa0d8a71fb773a60038a7b Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 17:36:24 +0000 Subject: [PATCH 02/16] Updated test dependencies --- Directory.Packages.props | 11 +++++----- .../EFCore5DbContextTests.cs | 4 ++-- .../ServiceCollectionExtensionsTests.cs | 4 ++-- ...ggerServiceApplicationDependenciesTests.cs | 10 +++++----- .../TriggerSessionTests.cs | 20 +++++++++---------- .../TriggeredDbContextTests.cs | 4 ++-- .../TriggeredSessionExtensionsTests.cs | 16 +++++++-------- 7 files changed, 34 insertions(+), 35 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 00b8396..ae091c2 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -8,11 +8,10 @@ - - - - - - + + + + + \ No newline at end of file diff --git a/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs b/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs index 5d8aec1..5148a43 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs @@ -131,7 +131,7 @@ public void SaveChanges_CascadingCall_ReturnsActiveTriggerSession() subject.SaveChanges(); - Assert.Equal(1, subject.TriggerStub.BeforeSaveInvocations.Count); + Assert.Single(subject.TriggerStub.BeforeSaveInvocations); } [Fact] @@ -163,7 +163,7 @@ public async Task SaveChangesAsync_CascadingCall_ReturnsActiveTriggerSession() await subject.SaveChangesAsync(); - Assert.Equal(1, subject.TriggerStub.BeforeSaveInvocations.Count); + Assert.Single(subject.TriggerStub.BeforeSaveInvocations); } [Fact] diff --git a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs index 3050d96..1a98283 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs @@ -93,7 +93,7 @@ public void AddTriggeredDbContext_ReusesScopedServiceProvider() var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; Assert.NotNull(triggerStub); - Assert.Equal(1, triggerStub.BeforeSaveInvocations.Count); + Assert.Single(triggerStub.BeforeSaveInvocations); } @@ -119,7 +119,7 @@ public void AddTriggeredDbContextPool_ReusesScopedServiceProvider() var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; Assert.NotNull(triggerStub); - Assert.Equal(1, triggerStub.BeforeSaveInvocations.Count); + Assert.Single(triggerStub.BeforeSaveInvocations); } [Fact] diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs index 8afec31..03a826d 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs @@ -43,7 +43,7 @@ void SimulateRequest() using var serviceScope = applicationServiceProvider.CreateScope(); var dbContext = serviceScope.ServiceProvider.GetRequiredService(); var triggerStub = serviceScope.ServiceProvider.GetRequiredService>() as TriggerStub; - Assert.Equal(0, triggerStub.BeforeSaveInvocations.Count); + Assert.Empty(triggerStub.BeforeSaveInvocations); dbContext.Add(new TestModel { }); dbContext.SaveChanges(); @@ -75,7 +75,7 @@ public void ScopedTriggers_NoScopedApplicationServiceProvider_ForPooledDbContext var triggerStub = serviceScope.ServiceProvider.GetRequiredService>() as TriggerStub; - Assert.Equal(0, triggerStub.BeforeSaveInvocations.Count); + Assert.Empty(triggerStub.BeforeSaveInvocations); } @@ -106,7 +106,7 @@ public void ScopedTriggers_WithScopedApplicationServiceProvider_ForDbContext() var triggerStub = scopedServiceProvider.GetRequiredService>() as TriggerStub; - Assert.Equal(1, triggerStub.BeforeSaveInvocations.Count); + Assert.Single(triggerStub.BeforeSaveInvocations); } @@ -137,7 +137,7 @@ public void ScopedTriggers_WithScopedApplicationServiceProvider_ForPooledDbConte var triggerStub = scopedServiceProvider.GetRequiredService>() as TriggerStub; - Assert.Equal(1, triggerStub.BeforeSaveInvocations.Count); + Assert.Single(triggerStub.BeforeSaveInvocations); } [Fact] @@ -169,7 +169,7 @@ void SimulateRequest() var triggerStub = scopedServiceProvider.GetRequiredService>() as TriggerStub; - Assert.Equal(1, triggerStub.BeforeSaveInvocations.Count); + Assert.Single(triggerStub.BeforeSaveInvocations); } SimulateRequest(); diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs index fe850f7..fe739d9 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs @@ -112,7 +112,7 @@ public void RaiseBeforeSaveTriggers_RaisesOnceOnSimpleAddition() subject.RaiseBeforeSaveTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeSaveInvocations.Count); + Assert.Single(context.TriggerStub.BeforeSaveInvocations); } [Fact] @@ -128,7 +128,7 @@ public async Task RaiseBeforeSaveAsyncTriggers_RaisesOnceOnSimpleAddition() await subject.RaiseBeforeSaveAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeSaveAsyncInvocations.Count); + Assert.Single(context.TriggerStub.BeforeSaveAsyncInvocations); } [Fact] @@ -173,7 +173,7 @@ public void RaiseAfterSaveTriggers_RaisesOnceOnSimpleAddition() subject.DiscoverChanges(); subject.RaiseAfterSaveTriggers(); - Assert.Equal(1, context.TriggerStub.AfterSaveInvocations.Count); + Assert.Single(context.TriggerStub.AfterSaveInvocations); } [Fact] @@ -190,7 +190,7 @@ public async Task RaiseAfterSaveAsyncTriggers_RaisesOnceOnSimpleAddition() subject.DiscoverChanges(); await subject.RaiseAfterSaveAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.AfterSaveAsyncInvocations.Count); + Assert.Single(context.TriggerStub.AfterSaveAsyncInvocations); } [Fact] @@ -383,7 +383,7 @@ public void RaiseAfterSaveFailedTriggers_OnException_RaisesSubsequentTriggers() subject.DiscoverChanges(); subject.RaiseAfterSaveFailedTriggers(new Exception()); - Assert.Equal(1, context.TriggerStub.AfterSaveFailedInvocations.Count); + Assert.Single(context.TriggerStub.AfterSaveFailedInvocations); } @@ -401,7 +401,7 @@ public async Task RaiseAfterSaveFailedAsyncTriggers_OnException_RaisesSubsequent subject.DiscoverChanges(); await subject.RaiseAfterSaveFailedAsyncTriggers(new Exception()); - Assert.Equal(1, context.TriggerStub.AfterSaveFailedAsyncInvocations.Count); + Assert.Single(context.TriggerStub.AfterSaveFailedAsyncInvocations); } [Fact] @@ -445,9 +445,9 @@ public void RaiseBeforeSaveTriggers_OnExceptionAndRecall_SkipsPreviousTriggers() subject.RaiseBeforeSaveTriggers(); } - Assert.Equal(1, firstTrigger.BeforeSaveInvocations.Count); - Assert.Equal(1, secondTrigger.BeforeSaveInvocations.Count); - Assert.Equal(1, lastTrigger.BeforeSaveInvocations.Count); + Assert.Single(firstTrigger.BeforeSaveInvocations); + Assert.Single(secondTrigger.BeforeSaveInvocations); + Assert.Single(lastTrigger.BeforeSaveInvocations); } [Fact] @@ -517,7 +517,7 @@ public void RaiseTriggers_DisabledConfiguration_Noop() subject.RaiseBeforeSaveTriggers(); // assert - Assert.Equal(0, context.TriggerStub.BeforeSaveInvocations.Count); + Assert.Empty(context.TriggerStub.BeforeSaveInvocations); } } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs index 9ce3514..df03bea 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs @@ -53,7 +53,7 @@ public void RaiseBeforeCommitTriggers_DiscoveredChangesFromTriggeredDbContext_Ca subject.RaiseBeforeCommitTriggers(); - Assert.Equal(1, dbContext.TriggerStub.BeforeCommitInvocations.Count); + Assert.Single(dbContext.TriggerStub.BeforeCommitInvocations); } @@ -72,7 +72,7 @@ public void RaiseAfterCommitTriggers_DiscoveredChangesFromTriggeredDbContext_Cal subject.RaiseAfterCommitTriggers(); - Assert.Equal(1, dbContext.TriggerStub.AfterCommitInvocations.Count); + Assert.Single(dbContext.TriggerStub.AfterCommitInvocations); } } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs index 667506a..f4db1b6 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs @@ -80,7 +80,7 @@ public void RaiseBeforeCommitTriggers_RaisesOnceOnSimpleAddition() session.DiscoverChanges(); session.RaiseBeforeCommitTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeCommitInvocations.Count); + Assert.Single(context.TriggerStub.BeforeCommitInvocations); } [Fact] @@ -97,7 +97,7 @@ public async Task RaiseBeforeCommitAsyncTriggers_RaisesOnceOnSimpleAddition() session.DiscoverChanges(); await session.RaiseBeforeCommitAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeCommitAsyncInvocations.Count); + Assert.Single(context.TriggerStub.BeforeCommitAsyncInvocations); } [Fact] @@ -138,7 +138,7 @@ public void RaiseAfterCommitTriggers_RaisesOnceOnSimpleAddition() session.DiscoverChanges(); session.RaiseAfterCommitTriggers(); - Assert.Equal(1, context.TriggerStub.AfterCommitInvocations.Count); + Assert.Single(context.TriggerStub.AfterCommitInvocations); } [Fact] @@ -155,7 +155,7 @@ public async Task RaiseAfterCommitAsyncTriggers_RaisesOnceOnSimpleAddition() session.DiscoverChanges(); await session.RaiseAfterCommitAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.AfterCommitAsyncInvocations.Count); + Assert.Single(context.TriggerStub.AfterCommitAsyncInvocations); } [Fact] @@ -196,7 +196,7 @@ public void RaiseBeforeRollbackTriggers_RaisesOnceOnSimpleAddition() session.DiscoverChanges(); session.RaiseBeforeRollbackTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeRollbackInvocations.Count); + Assert.Single(context.TriggerStub.BeforeRollbackInvocations); } [Fact] @@ -213,7 +213,7 @@ public async Task RaiseBeforeRollbackAsyncTriggers_RaisesOnceOnSimpleAddition() session.DiscoverChanges(); await session.RaiseBeforeRollbackAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeRollbackAsyncInvocations.Count); + Assert.Single(context.TriggerStub.BeforeRollbackAsyncInvocations); } [Fact] @@ -254,7 +254,7 @@ public void RaiseAfterRollbackTriggers_RaisesOnceOnSimpleAddition() session.DiscoverChanges(); session.RaiseAfterRollbackTriggers(); - Assert.Equal(1, context.TriggerStub.AfterRollbackInvocations.Count); + Assert.Single(context.TriggerStub.AfterRollbackInvocations); } [Fact] @@ -271,7 +271,7 @@ public async Task RaiseAfterRollbackAsyncTriggers_RaisesOnceOnSimpleAddition() session.DiscoverChanges(); await session.RaiseAfterRollbackAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.AfterRollbackAsyncInvocations.Count); + Assert.Single(context.TriggerStub.AfterRollbackAsyncInvocations); } [Fact] From 1fbe52cd5d597d9b2747762c1c21dad68c2de73f Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 17:42:50 +0000 Subject: [PATCH 03/16] Cleaned up target framework reference --- Directory.Build.props | 1 + EntityFrameworkCore.Triggered.sln | 3 +++ benchmarks/Directory.Build.props | 6 ------ ...ntityFrameworkCore.Triggered.Benchmarks.csproj | 2 +- samples/1 - HelloWorld/1 - HelloWorld.csproj | 1 - .../2 - PrimarySchool/2 - PrimarySchool.csproj | 1 - .../3 - StudentManagerAspNetCore.csproj | 1 - samples/4 - BlazorTests/4 - BlazorTests.csproj | 3 +-- samples/Directory.Build.props | 6 ------ src/Directory.Build.props | 15 --------------- ...rameworkCore.Triggered.Extensions.Tests.csproj | 2 -- ...rameworkCore.Triggered.IntegrationTests.csproj | 2 -- .../EntityFrameworkCore.Triggered.Tests.csproj | 2 -- .../ServiceCollectionExtensionsTests.cs | 8 +++----- ...meworkCore.Triggered.Transactions.Tests.csproj | 2 -- 15 files changed, 9 insertions(+), 46 deletions(-) delete mode 100644 benchmarks/Directory.Build.props delete mode 100644 samples/Directory.Build.props diff --git a/Directory.Build.props b/Directory.Build.props index 5ba6f62..5ba3e3e 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,7 @@ + net6.0 true 9.0 enable diff --git a/EntityFrameworkCore.Triggered.sln b/EntityFrameworkCore.Triggered.sln index 64258d0..2afb505 100644 --- a/EntityFrameworkCore.Triggered.sln +++ b/EntityFrameworkCore.Triggered.sln @@ -4,6 +4,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 VisualStudioVersion = 17.0.31710.8 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EDFABD48-3C79-47AE-B84C-47CE2A52C20D}" + ProjectSection(SolutionItems) = preProject + src\Directory.Build.props = src\Directory.Build.props + EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{0FAE4F6A-93BB-453C-8FB4-B24A9F30DA59}" EndProject diff --git a/benchmarks/Directory.Build.props b/benchmarks/Directory.Build.props deleted file mode 100644 index a03941c..0000000 --- a/benchmarks/Directory.Build.props +++ /dev/null @@ -1,6 +0,0 @@ - - - true - 8.0 - - \ No newline at end of file diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj index 95a47f2..6722f17 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj @@ -1,7 +1,7 @@  - net6.0 Exe + disable AnyCPU diff --git a/samples/1 - HelloWorld/1 - HelloWorld.csproj b/samples/1 - HelloWorld/1 - HelloWorld.csproj index 9ac9676..dafcafd 100644 --- a/samples/1 - HelloWorld/1 - HelloWorld.csproj +++ b/samples/1 - HelloWorld/1 - HelloWorld.csproj @@ -2,7 +2,6 @@ Exe - net6.0 HelloWorld disable diff --git a/samples/2 - PrimarySchool/2 - PrimarySchool.csproj b/samples/2 - PrimarySchool/2 - PrimarySchool.csproj index 82980db..6a8d09a 100644 --- a/samples/2 - PrimarySchool/2 - PrimarySchool.csproj +++ b/samples/2 - PrimarySchool/2 - PrimarySchool.csproj @@ -2,7 +2,6 @@ Exe - net6.0 PrimarySchool disable diff --git a/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj b/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj index 58a35a5..d2adb4e 100644 --- a/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj +++ b/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj @@ -1,7 +1,6 @@  - net6.0 StudentManager disable diff --git a/samples/4 - BlazorTests/4 - BlazorTests.csproj b/samples/4 - BlazorTests/4 - BlazorTests.csproj index f05cc39..f5327f9 100644 --- a/samples/4 - BlazorTests/4 - BlazorTests.csproj +++ b/samples/4 - BlazorTests/4 - BlazorTests.csproj @@ -1,7 +1,6 @@ - + - net6.0 BlazorTests disable diff --git a/samples/Directory.Build.props b/samples/Directory.Build.props deleted file mode 100644 index a7ba454..0000000 --- a/samples/Directory.Build.props +++ /dev/null @@ -1,6 +0,0 @@ - - - 6.0.0 - 3.0.0 - - \ No newline at end of file diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 0b76bee..71dd1fc 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,21 +1,6 @@ - - net6.0 - EFCORETRIGGERED3 - - - - netstandard2.1 - EFCORETRIGGERED2 - - - - netstandard2.0 - EFCORETRIGGERED1 - - true true diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj b/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj index b21a6a7..22c674e 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj @@ -1,8 +1,6 @@  - net6.0 - false disable diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj index 56ccc9e..832ac40 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj @@ -1,8 +1,6 @@ - net6.0 - false disable diff --git a/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj b/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj index 2dc9b07..4234e8b 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj +++ b/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj @@ -1,8 +1,6 @@  - net6.0 - false disable diff --git a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs index 1a98283..819cb48 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs @@ -164,7 +164,6 @@ public void AddTriggeredDbContextPool_SupportAContractType() Assert.Equal(context1, context1); } -#if EFCORETRIGGERED2 || EFCORETRIGGERED3 [Fact] public void AddTriggeredDbContextFactory_ReusesScopedServiceProvider() { @@ -189,7 +188,7 @@ public void AddTriggeredDbContextFactory_ReusesScopedServiceProvider() var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; Assert.NotNull(triggerStub); - Assert.Equal(1, triggerStub.BeforeSaveInvocations.Count); + Assert.Single(triggerStub.BeforeSaveInvocations); } [Fact] @@ -217,7 +216,7 @@ public void AddTriggeredDbContextFactory_WithCustomFactory_ReusesScopedServicePr var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; Assert.NotNull(triggerStub); - Assert.Equal(1, triggerStub.BeforeSaveInvocations.Count); + Assert.Single(triggerStub.BeforeSaveInvocations); } [Fact] @@ -244,8 +243,7 @@ public void AddTriggeredPooledDbContextFactory_ReusesScopedServiceProvider() var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; Assert.NotNull(triggerStub); - Assert.Equal(1, triggerStub.BeforeSaveInvocations.Count); + Assert.Single(triggerStub.BeforeSaveInvocations); } -#endif } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj b/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj index 60bbddb..6d4d2e8 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj @@ -1,8 +1,6 @@ - net6.0 - false disable From 3bd7ec62bce2bcbe2e31e6698448df4073ea36f9 Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 17:44:43 +0000 Subject: [PATCH 04/16] Updated to dotnet and efcore 8 --- Directory.Build.props | 2 +- Directory.Packages.props | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 5ba3e3e..8ac8124 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,7 +1,7 @@ - net6.0 + net8.0 true 9.0 enable diff --git a/Directory.Packages.props b/Directory.Packages.props index ae091c2..e7da195 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -4,10 +4,10 @@ - - - - + + + + From 12b78edf0728bc456c9c3c6b00dde18115cf612f Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 17:45:09 +0000 Subject: [PATCH 05/16] Uses C# 12 --- Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index 8ac8124..4ba8668 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -3,7 +3,7 @@ net8.0 true - 9.0 + 12.0 enable true README.md From d226f0ecffa2365c77d92f64c02d4506744a2041 Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 18:04:37 +0000 Subject: [PATCH 06/16] First round of code cleanup and modernization --- .editorconfig | 76 ++++++++++ .../ApplicationContext.cs | 22 +-- .../EmbracingFeaturesBenchmarks.cs | 6 +- .../PlainOverheadBenchmarks.cs | 15 +- .../Program.cs | 5 +- .../SetStudentRegistrationDateTrigger.cs | 7 +- .../SignStudentUpForMandatoryCourses.cs | 11 +- .../Triggers/StudentAssignRegistrationDate.cs | 2 - .../2 - PrimarySchool/ApplicationDbContext.cs | 7 +- .../StudentSignupToMandatoryCourses.cs | 11 +- .../ApplicationDbContext.cs | 7 +- .../Pages/Audits/Index.cshtml.cs | 14 +- .../Pages/Courses/Create.cshtml.cs | 14 +- .../Pages/Courses/Delete.cshtml.cs | 9 +- .../Pages/Courses/Details.cshtml.cs | 9 +- .../Pages/Courses/Edit.cshtml.cs | 14 +- .../Pages/Courses/Index.cshtml.cs | 14 +- .../Pages/Error.cshtml.cs | 14 +- .../Pages/Index.cshtml.cs | 9 +- .../Pages/Students/Create.cshtml.cs | 14 +- .../Pages/Students/Delete.cshtml.cs | 9 +- .../Pages/Students/Details.cshtml.cs | 9 +- .../Pages/Students/Edit.cshtml.cs | 14 +- .../Pages/Students/Index.cshtml.cs | 14 +- .../3 - StudentManagerAspNetCore/Program.cs | 5 +- .../3 - StudentManagerAspNetCore/Startup.cs | 9 +- .../Triggers/Courses/AutoSignupStudents.cs | 9 +- .../BlockRemovalWhenCourseIsMandatory.cs | 11 +- .../StudentCourses/SendWelcomingEmail.cs | 16 +-- .../Students/AssignRegistrationDate.cs | 7 +- .../Students/SignupToMandatoryCourses.cs | 9 +- .../Traits/Audited/CreateAuditRecord.cs | 11 +- .../Traits/SoftDelete/EnsureSoftDelete.cs | 11 +- .../4 - BlazorTests/ApplicationDbContext.cs | 7 +- .../Data/WeatherForecastService.cs | 6 +- samples/4 - BlazorTests/EventAggregator.cs | 5 +- samples/4 - BlazorTests/Pages/Error.cshtml.cs | 14 +- samples/4 - BlazorTests/Program.cs | 5 +- samples/4 - BlazorTests/Startup.cs | 9 +- .../Triggers/Counts/PublishCountAddedEvent.cs | 13 +- .../Triggers/Counts/SetCreatedOn.cs | 7 +- .../TriggerSessionConfiguration.cs | 8 +- .../ServiceCollectionExtensions.cs | 9 +- .../TriggerContextExtensions.cs | 6 - ...TriggersContextOptionsBuilderExtensions.cs | 5 +- .../IAfterCommitTrigger.cs | 5 +- .../IAfterRollbackTrigger.cs | 5 +- .../IBeforeCommitTrigger.cs | 5 +- .../IAfterCommitCompletedTrigger.cs | 5 +- .../Lifecycles/IAfterCommitStartingTrigger.cs | 5 +- .../IBeforeCommitCompletedTrigger.cs | 5 +- .../IBeforeCommitStartingTrigger.cs | 5 +- ...TriggersContextOptionsBuilderExtensions.cs | 5 +- .../Internal/AfterCommitTriggerDescriptor.cs | 2 - .../AfterRollbackTriggerDescriptor.cs | 2 - .../Internal/BeforeCommitTriggerDescriptor.cs | 2 - .../BeforeRollbackTriggerDescriptor.cs | 2 - .../TriggeredSessionExtensions.cs | 130 ++++-------------- .../Extensions/DbContextExtensions.cs | 7 +- .../Extensions/ServiceCollectionExtensions.cs | 2 +- .../TriggersDbContextOptionsExtensions.cs | 5 +- .../Internal/TriggersOptionExtension.cs | 42 ++---- .../Infrastructure/Internal/TypeHelpers.cs | 5 +- .../TriggersContextOptionsBuilder.cs | 9 +- ...plicationTriggerServiceProviderAccessor.cs | 11 +- ...ascadingTriggerContextDiscoveryStrategy.cs | 12 +- .../AfterSaveFailedTriggerDescriptor.cs | 3 - .../Descriptors/AfterSaveTriggerDescriptor.cs | 2 - .../BeforeSaveTriggerDescriptor.cs | 2 - .../Internal/EntityStateBagManager.cs | 6 +- .../Internal/HybridServiceProvider.cs | 12 +- .../Internal/ITriggerTypeRegistryService.cs | 1 - ...ascadingTriggerContextDiscoveryStrategy.cs | 9 +- .../Internal/TriggerContextDescriptor.cs | 19 +-- .../Internal/TriggerContextFactory.cs | 3 +- .../Internal/TriggerContextTracker.cs | 17 +-- .../Internal/TriggerDescriptorComparer.cs | 20 +-- .../Internal/TriggerDiscoveryService.cs | 43 ++---- .../Internal/TriggerFactory.cs | 11 +- .../Internal/TriggerInstanceFactory.cs | 19 +-- .../TriggerSessionSaveChangesInterceptor.cs | 6 +- .../Internal/TriggerTypeDescriptorHelpers.cs | 9 +- .../Internal/TriggerTypeRegistry.cs | 13 +- .../Internal/TriggerTypeRegistryService.cs | 1 - .../Internal/TriggeredDbContextFactory.cs | 31 ++--- .../TriggerContext.cs | 18 +-- .../TriggerService.cs | 7 +- .../TriggerSession.cs | 81 +++-------- .../AbstractTrigger.cs | 5 - .../ServiceCollectionExtensionsTests.cs | 9 +- .../TriggerContextExtensionsTests.cs | 7 +- ...gerContextOptionsBuilderExtensionsTests.cs | 6 +- .../ApplicationDbContext.cs | 19 +-- .../Triggers/SoftDelete.cs | 9 +- .../EntityBags/ApplicationDbContext.cs | 6 +- .../EntityBags/EntityBagsTestScenario.cs | 8 +- .../EntityBags/Triggers/SoftDeleteTrigger.cs | 14 +- .../Triggers/StampModifiedOnTrigger.cs | 5 - .../LifetimeTests/ApplicationDbContext.cs | 6 +- .../Triggers/Users/ScopedTrigger.cs | 5 +- .../Triggers/Users/SingletonTrigger.cs | 5 +- .../Triggers/Users/TransientTrigger.cs | 5 +- .../SampleStore/ApplicationDbContext.cs | 9 +- .../Triggers/Users/SoftDeleteUsers.cs | 9 +- .../EFCore5DbContextTests.cs | 11 +- .../Extensions/DbContextExtensionTests.cs | 6 +- .../ServiceCollectionExtensionsTests.cs | 12 +- .../AfterSaveFailedTriggerDescriptorTests.cs | 2 - .../AfterSaveTriggerDescriptorTests.cs | 4 +- .../BeforeSaveTriggerDescriptorTests.cs | 4 +- .../Internal/EntityBagStateManagerTests.cs | 7 +- .../Internal/TriggerDescriptorTests.cs | 2 - .../Internal/TriggerDiscoveryServiceTests.cs | 9 +- .../Internal/TriggerFactoryTests.cs | 20 +-- .../Internal/TriggerInstanceFactoryTests.cs | 11 +- ...iggerSessionSaveChangesInterceptorTests.cs | 12 +- .../Stubs/BeforeSaveDelegatingTrigger.cs | 9 +- .../Stubs/EventDefinitionBaseStub.cs | 7 +- .../Stubs/TriggerDiscoveryServiceStub.cs | 9 +- .../TriggerServiceProviderAccessorStub.cs | 9 +- .../Stubs/TriggerSessionStub.cs | 97 +++++-------- .../Stubs/TriggerStub.cs | 10 +- ...ggerServiceApplicationDependenciesTests.cs | 10 +- .../TriggeredDbContextFactoryTests.cs | 27 +--- .../AfterCommitTriggerDescriptorTests.cs | 3 +- .../AfterRollbackTriggerDescriptorTests.cs | 3 +- .../BeforeCommitTriggerDescriptorTests.cs | 3 +- .../BeforeRollbackTriggerDescriptorTests.cs | 3 +- .../Stubs/TriggerStub.cs | 58 +++----- 129 files changed, 427 insertions(+), 1160 deletions(-) diff --git a/.editorconfig b/.editorconfig index 30882e4..5f2d62c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -131,3 +131,79 @@ dotnet_naming_symbols.instance_fields.applicable_kinds = field dotnet_naming_style.instance_field_style.capitalization = camel_case dotnet_naming_style.instance_field_style.required_prefix = _ +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_style_namespace_declarations = block_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_top_level_statements = true:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_throw_expression = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_space_around_binary_operators = before_and_after +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent +csharp_style_prefer_readonly_struct = true:suggestion +csharp_prefer_static_local_function = true:suggestion +csharp_style_prefer_readonly_struct_member = true:suggestion +csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent +csharp_style_conditional_delegate_call = true:suggestion +csharp_style_prefer_switch_expression = true:suggestion +csharp_style_prefer_pattern_matching = true:silent +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion + +[*.{cs,vb}] +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion +dotnet_style_namespace_match_folder = true:suggestion +dotnet_style_readonly_field = true:suggestion +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion +dotnet_style_require_accessibility_modifiers = never:silent +dotnet_style_allow_multiple_blank_lines_experimental = true:silent +dotnet_style_allow_statement_immediately_after_block_experimental = true:silent +dotnet_code_quality_unused_parameters = all:suggestion +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:silent \ No newline at end of file diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs index 0fa3cb8..7a7948c 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs @@ -47,16 +47,9 @@ public interface IApplicationContextContract : IDisposable DbSet StudentCourses { get; set; } } - public class ApplicationContext : DbContext, IApplicationContextContract + public class ApplicationContext(DbContextOptions options) : DbContext(options), IApplicationContextContract { - public ApplicationContext(DbContextOptions options) : base(options) - { - } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity().HasKey(x => new { x.StudentId, x.CourseId }); - } + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasKey(x => new { x.StudentId, x.CourseId }); public DbSet Students { get; set; } @@ -65,16 +58,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public DbSet StudentCourses { get; set; } } - public class TriggeredApplicationContext : DbContext, IApplicationContextContract + public class TriggeredApplicationContext(DbContextOptions options) : DbContext(options), IApplicationContextContract { - public TriggeredApplicationContext(DbContextOptions options) : base(options) - { - } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity().HasKey(x => new { x.StudentId, x.CourseId }); - } + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasKey(x => new { x.StudentId, x.CourseId }); public DbSet Students { get; set; } diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs index 4cdf2d4..3c92432 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs @@ -12,9 +12,7 @@ public class EmbracingFeaturesBenchmarks private IServiceProvider _serviceProvider; [GlobalSetup] - public void GlobalSetup() - { - _serviceProvider = new ServiceCollection() + public void GlobalSetup() => _serviceProvider = new ServiceCollection() .AddDbContext(options => { options .UseInMemoryDatabase(nameof(WithDbContext)); @@ -29,8 +27,6 @@ public void GlobalSetup() }) .BuildServiceProvider(); - } - [Params(50)] public int OuterBatches; diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs index 00f396f..9c0ca0f 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs @@ -12,9 +12,7 @@ public class PlainOverheadBenchmarks IServiceProvider _serviceProvider; [GlobalSetup] - public void GlobalSetup() - { - _serviceProvider = new ServiceCollection() + public void GlobalSetup() => _serviceProvider = new ServiceCollection() .AddDbContext(options => { options .UseInMemoryDatabase(nameof(WithDbContext)); @@ -25,7 +23,6 @@ public void GlobalSetup() .UseTriggers(); }) .BuildServiceProvider(); - } [Params(50)] public int OuterBatches; @@ -89,15 +86,9 @@ void Execute() } [Benchmark(Baseline = true)] - public void WithDbContext() - { - Execute(); - } + public void WithDbContext() => Execute(); [Benchmark] - public void WithTriggeredDbContext() - { - Execute(); - } + public void WithTriggeredDbContext() => Execute(); } } diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Program.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Program.cs index af59e17..707fe9e 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Program.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Program.cs @@ -5,9 +5,6 @@ namespace EntityFrameworkCore.Triggered.Benchmarks { public class Program { - public static void Main(string[] args) - { - BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, DefaultConfig.Instance.WithOption(ConfigOptions.DisableOptimizationsValidator, true)); - } + public static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, DefaultConfig.Instance.WithOption(ConfigOptions.DisableOptimizationsValidator, true)); } } \ No newline at end of file diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs index 9a1f2cf..4203f97 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs @@ -1,14 +1,9 @@ using System; -using System.Threading; -using System.Threading.Tasks; namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers { public class SetStudentRegistrationDateTrigger : IBeforeSaveTrigger { - public void BeforeSave(ITriggerContext context) - { - context.Entity.RegistrationDate = DateTimeOffset.Now; - } + public void BeforeSave(ITriggerContext context) => context.Entity.RegistrationDate = DateTimeOffset.Now; } } diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs index 5cd3288..3e755a8 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs @@ -1,17 +1,10 @@ using System.Linq; -using System.Threading; -using System.Threading.Tasks; namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers { - public class SignStudentUpForMandatoryCourses : IBeforeSaveTrigger + public class SignStudentUpForMandatoryCourses(TriggeredApplicationContext applicationContext) : IBeforeSaveTrigger { - readonly TriggeredApplicationContext _applicationContext; - - public SignStudentUpForMandatoryCourses(TriggeredApplicationContext applicationContext) - { - _applicationContext = applicationContext; - } + readonly TriggeredApplicationContext _applicationContext = applicationContext; public void BeforeSave(ITriggerContext context) { diff --git a/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs b/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs index 417f1ea..47f3566 100644 --- a/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs +++ b/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs @@ -1,6 +1,4 @@ using System; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered; namespace PrimarySchool.Triggers diff --git a/samples/2 - PrimarySchool/ApplicationDbContext.cs b/samples/2 - PrimarySchool/ApplicationDbContext.cs index 2296101..cc883f2 100644 --- a/samples/2 - PrimarySchool/ApplicationDbContext.cs +++ b/samples/2 - PrimarySchool/ApplicationDbContext.cs @@ -34,13 +34,8 @@ public class StudentCourse } - public class ApplicationDbContext : DbContext + public class ApplicationDbContext(DbContextOptions options) : DbContext(options) { - public ApplicationDbContext(DbContextOptions options) : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() diff --git a/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs b/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs index 5b6eb32..7b01187 100644 --- a/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs +++ b/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs @@ -1,18 +1,11 @@ using System.Linq; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered; namespace PrimarySchool.Triggers { - public class StudentSignupToMandatoryCourses : IBeforeSaveTrigger + public class StudentSignupToMandatoryCourses(ApplicationDbContext applicationContext) : IBeforeSaveTrigger { - readonly ApplicationDbContext _applicationContext; - - public StudentSignupToMandatoryCourses(ApplicationDbContext applicationContext) - { - _applicationContext = applicationContext; - } + readonly ApplicationDbContext _applicationContext = applicationContext; public void BeforeSave(ITriggerContext context) { diff --git a/samples/3 - StudentManagerAspNetCore/ApplicationDbContext.cs b/samples/3 - StudentManagerAspNetCore/ApplicationDbContext.cs index fe8f98c..572fdec 100644 --- a/samples/3 - StudentManagerAspNetCore/ApplicationDbContext.cs +++ b/samples/3 - StudentManagerAspNetCore/ApplicationDbContext.cs @@ -3,13 +3,8 @@ namespace StudentManager { - public class ApplicationDbContext : DbContext + public class ApplicationDbContext(DbContextOptions options) : DbContext(options) { - public ApplicationDbContext(DbContextOptions options) : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs index 4d80d38..074b15c 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs @@ -5,20 +5,12 @@ namespace StudentManager.Pages { - public class AuditsModel : PageModel + public class AuditsModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; - - public AuditsModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } + private readonly StudentManager.ApplicationDbContext _context = context; public IList Audit { get; set; } - public async Task OnGetAsync() - { - Audit = await _context.Audits.ToListAsync(); - } + public async Task OnGetAsync() => Audit = await _context.Audits.ToListAsync(); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs index 5cbbbb3..c48c76f 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs @@ -4,19 +4,11 @@ namespace StudentManager.Pages.Courses { - public class CreateModel : PageModel + public class CreateModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; + private readonly StudentManager.ApplicationDbContext _context = context; - public CreateModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } - - public IActionResult OnGet() - { - return Page(); - } + public IActionResult OnGet() => Page(); [BindProperty] public Course Course { get; set; } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs index 26a069d..88d8709 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs @@ -5,14 +5,9 @@ namespace StudentManager.Pages.Courses { - public class DeleteModel : PageModel + public class DeleteModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; - - public DeleteModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } + private readonly StudentManager.ApplicationDbContext _context = context; [BindProperty] public Course Course { get; set; } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs index 4dbe97f..13245ed 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs @@ -5,14 +5,9 @@ namespace StudentManager.Pages.Courses { - public class DetailsModel : PageModel + public class DetailsModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; - - public DetailsModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } + private readonly StudentManager.ApplicationDbContext _context = context; public Course Course { get; set; } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs index 32dfe5b..e9e4cc8 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs @@ -6,14 +6,9 @@ namespace StudentManager.Pages.Courses { - public class EditModel : PageModel + public class EditModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; - - public EditModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } + private readonly StudentManager.ApplicationDbContext _context = context; [BindProperty] public Course Course { get; set; } @@ -64,9 +59,6 @@ public async Task OnPostAsync() return RedirectToPage("./Index"); } - private bool CourseExists(int id) - { - return _context.Courses.Any(e => e.Id == id); - } + private bool CourseExists(int id) => _context.Courses.Any(e => e.Id == id); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs index 040f3aa..50023c2 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs @@ -5,20 +5,12 @@ namespace StudentManager.Pages.Courses { - public class IndexModel : PageModel + public class IndexModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; - - public IndexModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } + private readonly StudentManager.ApplicationDbContext _context = context; public IList Course { get; set; } - public async Task OnGetAsync() - { - Course = await _context.Courses.IgnoreQueryFilters().ToListAsync(); - } + public async Task OnGetAsync() => Course = await _context.Courses.IgnoreQueryFilters().ToListAsync(); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs index 2f202d7..4dc505b 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs @@ -6,22 +6,14 @@ namespace StudentManager.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] - public class ErrorModel : PageModel + public class ErrorModel(ILogger logger) : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - private readonly ILogger _logger; + private readonly ILogger _logger = logger; - public ErrorModel(ILogger logger) - { - _logger = logger; - } - - public void OnGet() - { - RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; - } + public void OnGet() => RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs index f51a557..dcae617 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs @@ -3,14 +3,9 @@ namespace StudentManager.Pages { - public class IndexModel : PageModel + public class IndexModel(ILogger logger) : PageModel { - private readonly ILogger _logger; - - public IndexModel(ILogger logger) - { - _logger = logger; - } + private readonly ILogger _logger = logger; public void OnGet() { diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs index 3dce874..d6a1ee9 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs @@ -4,19 +4,11 @@ namespace StudentManager.Pages.Students { - public class CreateModel : PageModel + public class CreateModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; + private readonly StudentManager.ApplicationDbContext _context = context; - public CreateModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } - - public IActionResult OnGet() - { - return Page(); - } + public IActionResult OnGet() => Page(); [BindProperty] public Student Student { get; set; } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs index 9422a97..9147cb0 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs @@ -5,14 +5,9 @@ namespace StudentManager.Pages.Students { - public class DeleteModel : PageModel + public class DeleteModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; - - public DeleteModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } + private readonly StudentManager.ApplicationDbContext _context = context; [BindProperty] public Student Student { get; set; } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs index cd1a592..5d5eae1 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs @@ -5,14 +5,9 @@ namespace StudentManager.Pages.Students { - public class DetailsModel : PageModel + public class DetailsModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; - - public DetailsModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } + private readonly StudentManager.ApplicationDbContext _context = context; public Student Student { get; set; } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs index bfa16e3..bfdbb01 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs @@ -6,14 +6,9 @@ namespace StudentManager.Pages.Students { - public class EditModel : PageModel + public class EditModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; - - public EditModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } + private readonly StudentManager.ApplicationDbContext _context = context; [BindProperty] public Student Student { get; set; } @@ -64,9 +59,6 @@ public async Task OnPostAsync() return RedirectToPage("./Index"); } - private bool StudentExists(int id) - { - return _context.Students.Any(e => e.Id == id); - } + private bool StudentExists(int id) => _context.Students.Any(e => e.Id == id); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs index 5cab489..49beeeb 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs @@ -5,20 +5,12 @@ namespace StudentManager.Pages.Students { - public class IndexModel : PageModel + public class IndexModel(StudentManager.ApplicationDbContext context) : PageModel { - private readonly StudentManager.ApplicationDbContext _context; - - public IndexModel(StudentManager.ApplicationDbContext context) - { - _context = context; - } + private readonly StudentManager.ApplicationDbContext _context = context; public IList Student { get; set; } - public async Task OnGetAsync() - { - Student = await _context.Students.Include(x => x.Courses).ThenInclude(x => x.Course).ToListAsync(); - } + public async Task OnGetAsync() => Student = await _context.Students.Include(x => x.Courses).ThenInclude(x => x.Course).ToListAsync(); } } diff --git a/samples/3 - StudentManagerAspNetCore/Program.cs b/samples/3 - StudentManagerAspNetCore/Program.cs index b5d5e55..de55a78 100644 --- a/samples/3 - StudentManagerAspNetCore/Program.cs +++ b/samples/3 - StudentManagerAspNetCore/Program.cs @@ -5,10 +5,7 @@ namespace StudentManager { public class Program { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } + public static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) diff --git a/samples/3 - StudentManagerAspNetCore/Startup.cs b/samples/3 - StudentManagerAspNetCore/Startup.cs index 4f5394d..b4e6bb4 100644 --- a/samples/3 - StudentManagerAspNetCore/Startup.cs +++ b/samples/3 - StudentManagerAspNetCore/Startup.cs @@ -8,14 +8,9 @@ namespace StudentManager { - public class Startup + public class Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } = configuration; // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs index 5352135..b748525 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs @@ -6,14 +6,9 @@ namespace StudentManager.Triggers.Courses { - public class AutoSignupStudents : IBeforeSaveAsyncTrigger + public class AutoSignupStudents(ApplicationDbContext applicationContext) : IBeforeSaveAsyncTrigger { - readonly ApplicationDbContext _applicationContext; - - public AutoSignupStudents(ApplicationDbContext applicationContext) - { - _applicationContext = applicationContext; - } + readonly ApplicationDbContext _applicationContext = applicationContext; public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) { diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs index 673bd73..8ff1e24 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs @@ -5,20 +5,15 @@ namespace StudentManager.Triggers.StudentCourses { - public class BlockRemovalWhenCourseIsMandatory : IBeforeSaveAsyncTrigger + public class BlockRemovalWhenCourseIsMandatory(ApplicationDbContext applicationContext) : IBeforeSaveAsyncTrigger { - readonly ApplicationDbContext _applicationContext; - - public BlockRemovalWhenCourseIsMandatory(ApplicationDbContext applicationContext) - { - _applicationContext = applicationContext; - } + readonly ApplicationDbContext _applicationContext = applicationContext; public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) { if (context.ChangeType == ChangeType.Deleted) { - var course = await _applicationContext.Courses.FindAsync(new object[] { context.Entity.CourseId }, cancellationToken); + var course = await _applicationContext.Courses.FindAsync([context.Entity.CourseId], cancellationToken); if (course.IsMandatory) { throw new InvalidOperationException("Course is required"); diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs index 941291b..44cadfb 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs @@ -5,21 +5,15 @@ namespace StudentManager.Triggers.StudentCourses { - public class SendWelcomingEmail : IAfterSaveAsyncTrigger + public class SendWelcomingEmail(ApplicationDbContext applicationContext, EmailService emailService) : IAfterSaveAsyncTrigger { - readonly ApplicationDbContext _applicationContext; - readonly EmailService _emailService; - - public SendWelcomingEmail(ApplicationDbContext applicationContext, EmailService emailService) - { - _applicationContext = applicationContext; - _emailService = emailService; - } + readonly ApplicationDbContext _applicationContext = applicationContext; + readonly EmailService _emailService = emailService; public async Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) { - var student = await _applicationContext.Students.FindAsync(new object[] { context.Entity.StudentId }, cancellationToken); - var course = await _applicationContext.Courses.FindAsync(new object[] { context.Entity.CourseId }, cancellationToken); + var student = await _applicationContext.Students.FindAsync([context.Entity.StudentId], cancellationToken); + var course = await _applicationContext.Courses.FindAsync([context.Entity.CourseId], cancellationToken); _emailService.SendEmail(student, $"Welcoming {student.DisplayName} to the course: {course.DisplayName}"); } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs index dd2f3ca..8f11fe4 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs @@ -1,15 +1,10 @@ using System; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered; namespace StudentManager.Triggers.Students { public class AssignRegistrationDate : IBeforeSaveTrigger { - public void BeforeSave(ITriggerContext context) - { - context.Entity.RegistrationDate = DateTime.Today; - } + public void BeforeSave(ITriggerContext context) => context.Entity.RegistrationDate = DateTime.Today; } } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs index 9baea35..4c79120 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs @@ -6,14 +6,9 @@ namespace StudentManager.Triggers.Students { - public class SignupToMandatoryCourses : IBeforeSaveAsyncTrigger + public class SignupToMandatoryCourses(ApplicationDbContext applicationContext) : IBeforeSaveAsyncTrigger { - readonly ApplicationDbContext _applicationContext; - - public SignupToMandatoryCourses(ApplicationDbContext applicationContext) - { - _applicationContext = applicationContext; - } + readonly ApplicationDbContext _applicationContext = applicationContext; public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) { diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs index 4c2555b..24c31df 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs @@ -1,21 +1,14 @@ using System; using System.Linq; using System.Text; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered; using StudentManager.Traits; namespace StudentManager.Triggers.Traits.Audited { - public class CreateAuditRecord : IBeforeSaveTrigger + public class CreateAuditRecord(ApplicationDbContext applicationContext) : IBeforeSaveTrigger { - private readonly ApplicationDbContext _applicationContext; - - public CreateAuditRecord(ApplicationDbContext applicationContext) - { - _applicationContext = applicationContext; - } + private readonly ApplicationDbContext _applicationContext = applicationContext; public void BeforeSave(ITriggerContext context) { diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs index 71482a7..243554f 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs @@ -1,19 +1,12 @@ using System; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered; using StudentManager.Traits; namespace StudentManager.Triggers.Traits.SoftDelete { - class EnsureSoftDelete : IBeforeSaveTrigger + class EnsureSoftDelete(ApplicationDbContext applicationContext) : IBeforeSaveTrigger { - readonly ApplicationDbContext _applicationContext; - - public EnsureSoftDelete(ApplicationDbContext applicationContext) - { - _applicationContext = applicationContext; - } + readonly ApplicationDbContext _applicationContext = applicationContext; public void BeforeSave(ITriggerContext context) { diff --git a/samples/4 - BlazorTests/ApplicationDbContext.cs b/samples/4 - BlazorTests/ApplicationDbContext.cs index 39001ca..e9d7586 100644 --- a/samples/4 - BlazorTests/ApplicationDbContext.cs +++ b/samples/4 - BlazorTests/ApplicationDbContext.cs @@ -9,13 +9,8 @@ public class Count public DateTime CreatedOn { get; set; } } - public class ApplicationDbContext : DbContext + public class ApplicationDbContext(DbContextOptions options) : DbContext(options) { - public ApplicationDbContext(DbContextOptions options) : base(options) - { - - } - public DbSet Counts { get; set; } } diff --git a/samples/4 - BlazorTests/Data/WeatherForecastService.cs b/samples/4 - BlazorTests/Data/WeatherForecastService.cs index 9b4586a..7eec729 100644 --- a/samples/4 - BlazorTests/Data/WeatherForecastService.cs +++ b/samples/4 - BlazorTests/Data/WeatherForecastService.cs @@ -6,10 +6,10 @@ namespace BlazorTests.Data { public class WeatherForecastService { - private static readonly string[] Summaries = new[] - { + private readonly static string[] Summaries = + [ "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" - }; + ]; public Task GetForecastAsync(DateTime startDate) { diff --git a/samples/4 - BlazorTests/EventAggregator.cs b/samples/4 - BlazorTests/EventAggregator.cs index dbeb890..8995130 100644 --- a/samples/4 - BlazorTests/EventAggregator.cs +++ b/samples/4 - BlazorTests/EventAggregator.cs @@ -9,9 +9,6 @@ public class EventAggregator { public event Action CountAdded; - public void PublishCountAdded(Count count) - { - CountAdded?.Invoke(count); - } + public void PublishCountAdded(Count count) => CountAdded?.Invoke(count); } } diff --git a/samples/4 - BlazorTests/Pages/Error.cshtml.cs b/samples/4 - BlazorTests/Pages/Error.cshtml.cs index 3c4bc1a..2aaf9e8 100644 --- a/samples/4 - BlazorTests/Pages/Error.cshtml.cs +++ b/samples/4 - BlazorTests/Pages/Error.cshtml.cs @@ -7,22 +7,14 @@ namespace BlazorTests.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [IgnoreAntiforgeryToken] - public class ErrorModel : PageModel + public class ErrorModel(ILogger logger) : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - private readonly ILogger _logger; + private readonly ILogger _logger = logger; - public ErrorModel(ILogger logger) - { - _logger = logger; - } - - public void OnGet() - { - RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; - } + public void OnGet() => RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } diff --git a/samples/4 - BlazorTests/Program.cs b/samples/4 - BlazorTests/Program.cs index b3d94b9..3d9dd45 100644 --- a/samples/4 - BlazorTests/Program.cs +++ b/samples/4 - BlazorTests/Program.cs @@ -5,10 +5,7 @@ namespace BlazorTests { public class Program { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } + public static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) diff --git a/samples/4 - BlazorTests/Startup.cs b/samples/4 - BlazorTests/Startup.cs index c18eb56..ee79abf 100644 --- a/samples/4 - BlazorTests/Startup.cs +++ b/samples/4 - BlazorTests/Startup.cs @@ -7,14 +7,9 @@ namespace BlazorTests { - public class Startup + public class Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } = configuration; // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 diff --git a/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs b/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs index 5b47829..8e08e6d 100644 --- a/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs +++ b/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs @@ -1,17 +1,10 @@ -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; namespace BlazorTests.Triggers.Counts { - public class PublishCountAddedEvent : IAfterSaveTrigger + public class PublishCountAddedEvent(EventAggregator eventAggregator) : IAfterSaveTrigger { - private readonly EventAggregator _eventAggregator; - - public PublishCountAddedEvent(EventAggregator eventAggregator) - { - _eventAggregator = eventAggregator; - } + private readonly EventAggregator _eventAggregator = eventAggregator; public void AfterSave(ITriggerContext context) { diff --git a/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs b/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs index d0046a1..fc75579 100644 --- a/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs +++ b/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs @@ -1,15 +1,10 @@ using System; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered; namespace BlazorTests.Triggers.Counts { public class SetCreatedOn : IBeforeSaveTrigger { - public void BeforeSave(ITriggerContext context) - { - context.Entity.CreatedOn = DateTime.UtcNow; - } + public void BeforeSave(ITriggerContext context) => context.Entity.CreatedOn = DateTime.UtcNow; } } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/TriggerSessionConfiguration.cs b/src/EntityFrameworkCore.Triggered.Abstractions/TriggerSessionConfiguration.cs index 1ed8954..07f3ee6 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/TriggerSessionConfiguration.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/TriggerSessionConfiguration.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered { public record TriggerSessionConfiguration { diff --git a/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs b/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs index 2b8c382..43d1d38 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs @@ -10,7 +10,7 @@ namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { - static readonly Type[] _wellKnownTriggerTypes = new Type[] { + readonly static Type[] _wellKnownTriggerTypes = [ typeof(IBeforeSaveTrigger<>), typeof(IBeforeSaveAsyncTrigger<>), typeof(IAfterSaveTrigger<>), @@ -29,7 +29,7 @@ public static class ServiceCollectionExtensions typeof(IAfterSaveStartingAsyncTrigger), typeof(IAfterSaveCompletedTrigger), typeof(IAfterSaveCompletedAsyncTrigger) - }; + ]; static void RegisterTriggerTypes(Type triggerImplementationType, IServiceCollection services) { @@ -78,10 +78,7 @@ public static IServiceCollection AddAssemblyTriggers(this IServiceCollection ser public static IServiceCollection AddAssemblyTriggers(this IServiceCollection services, ServiceLifetime lifetime, params Assembly[] assemblies) { - if (assemblies is null) - { - throw new ArgumentNullException(nameof(assemblies)); - } + ArgumentNullException.ThrowIfNull(assemblies); var assemblyTypes = assemblies .SelectMany(x => x.GetTypes()) diff --git a/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs b/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs index 06473f2..89394ed 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs @@ -1,12 +1,6 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; -using Microsoft.EntityFrameworkCore.Metadata.Conventions; namespace EntityFrameworkCore.Triggered { diff --git a/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs b/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs index 4c6d297..cd77cdd 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs @@ -19,10 +19,7 @@ public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersCon public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersContextOptionsBuilder builder, ServiceLifetime lifetime, params Assembly[] assemblies) { - if (assemblies is null) - { - throw new ArgumentNullException(nameof(assemblies)); - } + ArgumentNullException.ThrowIfNull(assemblies); var assemblyTypes = assemblies .SelectMany(x => x.GetTypes()) diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitTrigger.cs index 8f8e1e4..a81d65e 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions { public interface IAfterCommitTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackTrigger.cs index 707e968..550347d 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions { public interface IAfterRollbackTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitTrigger.cs index a02fcd1..39c3d02 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions { public interface IBeforeCommitTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedTrigger.cs index de6f402..c984fb4 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles { public interface IAfterCommitCompletedTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingTrigger.cs index 1e852c6..706cd2c 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles { public interface IAfterCommitStartingTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedTrigger.cs index a27f173..07f9ec2 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles { public interface IBeforeCommitCompletedTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingTrigger.cs index 6ad799f..bb82bfe 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles { public interface IBeforeCommitStartingTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs b/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs index 4304f61..7124e3f 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs @@ -9,10 +9,7 @@ public static class TriggersContextOptionsBuilderExtensions { public static TriggersContextOptionsBuilder UseTransactionTriggers(this TriggersContextOptionsBuilder triggersContextOptionsBuilder) { - if (triggersContextOptionsBuilder is null) - { - throw new ArgumentNullException(nameof(triggersContextOptionsBuilder)); - } + ArgumentNullException.ThrowIfNull(triggersContextOptionsBuilder); return triggersContextOptionsBuilder .AddTriggerType(typeof(IBeforeCommitTrigger<>)) diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs index 9f6d366..f317b42 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs @@ -1,7 +1,5 @@ using System; using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs index 4b77080..b088ffc 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs @@ -1,7 +1,5 @@ using System; using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs index 68bf870..602eb40 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs @@ -1,7 +1,5 @@ using System; using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs index 184f27a..aacd54a 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs @@ -1,7 +1,5 @@ using System; using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs b/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs index 0832a01..28006ee 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs @@ -18,132 +18,79 @@ public static class TriggeredSessionExtensions public static void RaiseBeforeCommitTriggers(this ITriggerSession triggerSession) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } - - if (_beforeCommitTriggerContextDiscoveryStrategy == null) - { - _beforeCommitTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("BeforeCommit"); - } + ArgumentNullException.ThrowIfNull(triggerSession); + _beforeCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeCommit"); ((TriggerSession)triggerSession).RaiseTriggers(typeof(IBeforeCommitTrigger<>), null, _beforeCommitTriggerContextDiscoveryStrategy, entityType => new BeforeCommitTriggerDescriptor(entityType)); } public static Task RaiseBeforeCommitAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } - - if (_beforeCommitTriggerContextDiscoveryStrategy == null) - { - _beforeCommitTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("BeforeCommit"); - } + ArgumentNullException.ThrowIfNull(triggerSession); + _beforeCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeCommit"); return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IBeforeCommitAsyncTrigger<>), null, _beforeCommitTriggerContextDiscoveryStrategy, entityType => new BeforeCommitAsyncTriggerDescriptor(entityType), cancellationToken); } public static void RaiseAfterCommitTriggers(this ITriggerSession triggerSession) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); - if (_afterCommitTriggerContextDiscoveryStrategy == null) - { - _afterCommitTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("AfterCommit"); - } + _afterCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterCommit"); ((TriggerSession)triggerSession).RaiseTriggers(typeof(IAfterCommitTrigger<>), null, _afterCommitTriggerContextDiscoveryStrategy, entityType => new AfterCommitTriggerDescriptor(entityType)); } public static Task RaiseAfterCommitAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); - if (_afterCommitTriggerContextDiscoveryStrategy == null) - { - _afterCommitTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("AfterCommit"); - } + _afterCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterCommit"); return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IAfterCommitAsyncTrigger<>), null, _afterCommitTriggerContextDiscoveryStrategy, entityType => new AfterCommitAsyncTriggerDescriptor(entityType), cancellationToken); } public static void RaiseBeforeRollbackTriggers(this ITriggerSession triggerSession) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); - if (_beforeRollbackTriggerContextDiscoveryStrategy == null) - { - _beforeRollbackTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("BeforeRollback"); - } + _beforeRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeRollback"); ((TriggerSession)triggerSession).RaiseTriggers(typeof(IBeforeRollbackTrigger<>), null, _beforeRollbackTriggerContextDiscoveryStrategy, entityType => new BeforeRollbackTriggerDescriptor(entityType)); } public static Task RaiseBeforeRollbackAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); - if (_beforeRollbackTriggerContextDiscoveryStrategy == null) - { - _beforeRollbackTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("BeforeRollback"); - } + _beforeRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeRollback"); return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IBeforeRollbackAsyncTrigger<>), null, _beforeRollbackTriggerContextDiscoveryStrategy, entityType => new BeforeRollbackAsyncTriggerDescriptor(entityType), cancellationToken); } public static void RaiseAfterRollbackTriggers(this ITriggerSession triggerSession) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); - if (_afterRollbackTriggerContextDiscoveryStrategy == null) - { - _afterRollbackTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("AfterRollback"); - } + _afterRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterRollback"); ((TriggerSession)triggerSession).RaiseTriggers(typeof(IAfterRollbackTrigger<>), null, _afterRollbackTriggerContextDiscoveryStrategy, entityType => new AfterRollbackTriggerDescriptor(entityType)); } public static Task RaiseAfterRollbackAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); - if (_afterRollbackTriggerContextDiscoveryStrategy == null) - { - _afterRollbackTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("AfterRollback"); - } + _afterRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterRollback"); return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IAfterRollbackAsyncTrigger<>), null, _afterRollbackTriggerContextDiscoveryStrategy, entityType => new AfterRollbackAsyncTriggerDescriptor(entityType), cancellationToken); } public static void RaiseBeforeCommitStartingTriggers(this ITriggerSession triggerSession) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); if (triggerSession is not TriggerSession typedTriggerSession) { @@ -159,12 +106,9 @@ public static void RaiseBeforeCommitStartingTriggers(this ITriggerSession trigge } - public static async Task RaiseBeforeCommitStartingAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + public async static Task RaiseBeforeCommitStartingAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); if (triggerSession is not TriggerSession typedTriggerSession) { @@ -181,10 +125,7 @@ public static async Task RaiseBeforeCommitStartingAsyncTriggers(this ITriggerSes public static void RaiseBeforeCommitCompletedTriggers(this ITriggerSession triggerSession) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); if (triggerSession is not TriggerSession typedTriggerSession) { @@ -199,12 +140,9 @@ public static void RaiseBeforeCommitCompletedTriggers(this ITriggerSession trigg } } - public static async Task RaiseBeforeCommitCompletedAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + public async static Task RaiseBeforeCommitCompletedAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); if (triggerSession is not TriggerSession typedTriggerSession) { @@ -221,10 +159,7 @@ public static async Task RaiseBeforeCommitCompletedAsyncTriggers(this ITriggerSe public static void RaiseAfterCommitStartingTriggers(this ITriggerSession triggerSession) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); if (triggerSession is not TriggerSession typedTriggerSession) { @@ -239,12 +174,9 @@ public static void RaiseAfterCommitStartingTriggers(this ITriggerSession trigger } } - public static async Task RaiseAfterCommitStartingAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + public async static Task RaiseAfterCommitStartingAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); if (triggerSession is not TriggerSession typedTriggerSession) { @@ -261,10 +193,7 @@ public static async Task RaiseAfterCommitStartingAsyncTriggers(this ITriggerSess public static void RaiseAfterCommitCompletedTriggers(this ITriggerSession triggerSession) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); if (triggerSession is not TriggerSession typedTriggerSession) { @@ -279,12 +208,9 @@ public static void RaiseAfterCommitCompletedTriggers(this ITriggerSession trigge } } - public static async Task RaiseAfterCommitCompletedAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + public async static Task RaiseAfterCommitCompletedAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) { - if (triggerSession == null) - { - throw new ArgumentNullException(nameof(triggerSession)); - } + ArgumentNullException.ThrowIfNull(triggerSession); if (triggerSession is not TriggerSession typedTriggerSession) { diff --git a/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs b/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs index 93db627..131a330 100644 --- a/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs +++ b/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs @@ -1,6 +1,6 @@ using System; -using System.Threading.Tasks; using System.Threading; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -13,10 +13,7 @@ public static class DbContextExtensions /// public static ITriggerService GetTriggerService(this DbContext dbContext) { - if (dbContext is null) - { - throw new ArgumentNullException(nameof(dbContext)); - } + ArgumentNullException.ThrowIfNull(dbContext); return dbContext.GetService() ?? throw new InvalidOperationException("Triggers are not configured for this DbContext"); } diff --git a/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs b/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs index f72ef5c..48ed647 100644 --- a/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs +++ b/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs @@ -163,7 +163,7 @@ public static IServiceCollection AddTriggeredPooledDbContextFactory(th lifetime: ServiceLifetime.Scoped )); } - + if (serviceDescriptor?.ImplementationFactory != null) { var triggeredFactoryType = typeof(TriggeredDbContextFactory<>).MakeGenericType(typeof(TContext)); diff --git a/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs b/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs index 58a2b28..7c6eacc 100644 --- a/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs +++ b/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs @@ -15,10 +15,7 @@ public static DbContextOptionsBuilder UseTriggers(this DbCon public static DbContextOptionsBuilder UseTriggers(this DbContextOptionsBuilder optionsBuilder, Action? configure = null) { - if (optionsBuilder is null) - { - throw new ArgumentNullException(nameof(optionsBuilder)); - } + ArgumentNullException.ThrowIfNull(optionsBuilder); var extension = optionsBuilder.Options.FindExtension() ?? new TriggersOptionExtension(); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs index 3c24b89..1dc1bff 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs @@ -14,22 +14,16 @@ namespace EntityFrameworkCore.Triggered.Infrastructure.Internal { public class TriggersOptionExtension : IDbContextOptionsExtension { - sealed class ExtensionInfo : DbContextOptionsExtensionInfo + sealed class ExtensionInfo(IDbContextOptionsExtension extension) : DbContextOptionsExtensionInfo(extension) { private string? _logFragment; - public ExtensionInfo(IDbContextOptionsExtension extension) : base(extension) - { - } public override bool IsDatabaseProvider => false; public override string LogFragment { get { - if (_logFragment == null) - { - _logFragment = string.Empty; - } + _logFragment ??= string.Empty; return _logFragment; } @@ -39,10 +33,7 @@ public override string LogFragment public override void PopulateDebugInfo(IDictionary debugInfo) { - if (debugInfo == null) - { - throw new ArgumentNullException(nameof(debugInfo)); - } + ArgumentNullException.ThrowIfNull(debugInfo); debugInfo["Triggers:TriggersCount"] = (Extension._triggers?.Count() ?? 0).ToString(); debugInfo["Triggers:TriggerTypesCount"] = (Extension._triggerTypes?.Count() ?? 0).ToString(); @@ -83,8 +74,8 @@ public override int GetServiceProviderHashCode() public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is ExtensionInfo otherInfo - && Enumerable.SequenceEqual(Extension._triggers ?? Enumerable.Empty>(), otherInfo.Extension._triggers ?? Enumerable.Empty>()) - && Enumerable.SequenceEqual(Extension._triggerTypes ?? Enumerable.Empty(), otherInfo.Extension._triggerTypes ?? Enumerable.Empty()) + && Enumerable.SequenceEqual(Extension._triggers ?? [], otherInfo.Extension._triggers ?? []) + && Enumerable.SequenceEqual(Extension._triggerTypes ?? [], otherInfo.Extension._triggerTypes ?? []) && Extension._maxCascadeCycles == otherInfo.Extension._maxCascadeCycles && Extension._cascadeBehavior == otherInfo.Extension._cascadeBehavior && Extension._serviceProviderTransform == otherInfo.Extension._serviceProviderTransform; @@ -99,7 +90,7 @@ public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo public TriggersOptionExtension() { - _triggerTypes = new[] { + _triggerTypes = [ typeof(IBeforeSaveTrigger<>), typeof(IBeforeSaveAsyncTrigger<>), typeof(IAfterSaveTrigger<>), @@ -118,7 +109,7 @@ public TriggersOptionExtension() typeof(IAfterSaveStartingAsyncTrigger), typeof(IAfterSaveCompletedTrigger), typeof(IAfterSaveCompletedAsyncTrigger) - }; + ]; } public TriggersOptionExtension(TriggersOptionExtension copyFrom) @@ -139,7 +130,7 @@ public DbContextOptionsExtensionInfo Info public int MaxCascadeCycles => _maxCascadeCycles; public CascadeBehavior CascadeBehavior => _cascadeBehavior; - public IEnumerable<(object typeOrInstance, ServiceLifetime lifetime)> Triggers => _triggers ?? Enumerable.Empty<(object typeOrInstance, ServiceLifetime lifetime)>(); + public IEnumerable<(object typeOrInstance, ServiceLifetime lifetime)> Triggers => _triggers ?? []; public void ApplyServices(IServiceCollection services) { @@ -195,18 +186,15 @@ public void ApplyServices(IServiceCollection services) foreach (var triggerTypeImplementation in triggerTypeImplementations) { - if (triggerInstanceFactoryBuilder is null) - { - triggerInstanceFactoryBuilder = + triggerInstanceFactoryBuilder ??= Expression.Lambda>( Expression.New( - typeof(TriggerInstanceFactory<>).MakeGenericType(triggerServiceType).GetConstructor(new[] { typeof(object) })!, + typeof(TriggerInstanceFactory<>).MakeGenericType(triggerServiceType).GetConstructor([typeof(object)])!, instanceParamExpression ), instanceParamExpression ) .Compile(); - } var triggerTypeImplementationFactoryType = typeof(ITriggerInstanceFactory<>).MakeGenericType(triggerTypeImplementation); services.Add(new ServiceDescriptor(triggerTypeImplementationFactoryType, _ => triggerInstanceFactoryBuilder(triggerServiceInstance), lifetime)); @@ -280,10 +268,7 @@ public TriggersOptionExtension WithAdditionalTrigger(Type triggerType, ServiceLi public TriggersOptionExtension WithAdditionalTrigger(object instance) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } + ArgumentNullException.ThrowIfNull(instance); if (!TypeIsValidTrigger(instance.GetType())) { @@ -308,10 +293,7 @@ public TriggersOptionExtension WithAdditionalTrigger(object instance) public TriggersOptionExtension WithAdditionalTriggerType(Type triggerType) { - if (triggerType == null) - { - throw new ArgumentNullException(nameof(triggerType)); - } + ArgumentNullException.ThrowIfNull(triggerType); var clone = Clone(); diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs index 9d3aafd..9c2b745 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; namespace EntityFrameworkCore.Triggered.Infrastructure.Internal @@ -14,11 +13,11 @@ public static IEnumerable EnumerateTypeHierarchy(Type type) { Type? nextType = type; - while(nextType is not null) + while (nextType is not null) { yield return nextType; nextType = nextType.BaseType; - } while (nextType != null); + } while (nextType != null) ; } } } diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs index a9a9625..b2febe7 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs @@ -6,14 +6,9 @@ namespace EntityFrameworkCore.Triggered.Infrastructure { - public class TriggersContextOptionsBuilder + public class TriggersContextOptionsBuilder(DbContextOptionsBuilder optionsBuilder) { - readonly DbContextOptionsBuilder _optionsBuilder; - - public TriggersContextOptionsBuilder(DbContextOptionsBuilder optionsBuilder) - { - _optionsBuilder = optionsBuilder ?? throw new ArgumentNullException(nameof(optionsBuilder)); - } + readonly DbContextOptionsBuilder _optionsBuilder = optionsBuilder ?? throw new ArgumentNullException(nameof(optionsBuilder)); public TriggersContextOptionsBuilder AddTrigger() => AddTrigger(ServiceLifetime.Transient); diff --git a/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs b/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs index c69b6aa..3590528 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -18,10 +17,7 @@ public sealed class ApplicationTriggerServiceProviderAccessor : ITriggerServiceP public ApplicationTriggerServiceProviderAccessor(IServiceProvider internalServiceProvider, Func? scopedServiceProviderTransform) { - if (internalServiceProvider is null) - { - throw new ArgumentNullException(nameof(internalServiceProvider)); - } + ArgumentNullException.ThrowIfNull(internalServiceProvider); var dbContextOptions = internalServiceProvider.GetRequiredService(); var coreOptionsExtension = dbContextOptions.FindExtension() ?? throw new InvalidOperationException("No coreOptionsExtension configured"); @@ -35,10 +31,7 @@ public ApplicationTriggerServiceProviderAccessor(IServiceProvider internalServic _scopedServiceProviderTransform = scopedServiceProviderTransform; } - public void SetTriggerServiceProvider(IServiceProvider serviceProvider) - { - _applicationScopedServiceProvider = serviceProvider; - } + public void SetTriggerServiceProvider(IServiceProvider serviceProvider) => _applicationScopedServiceProvider = serviceProvider; public IServiceProvider GetTriggerServiceProvider() { diff --git a/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs index bc49b9c..2f8e84d 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs @@ -5,7 +5,7 @@ namespace EntityFrameworkCore.Triggered.Internal { - public class CascadingTriggerContextDiscoveryStrategy : ITriggerContextDiscoveryStrategy + public class CascadingTriggerContextDiscoveryStrategy(string name, bool skipDetectedChanges) : ITriggerContextDiscoveryStrategy { readonly static Action _discoveryStarted = LoggerMessage.Define( LogLevel.Debug, @@ -17,14 +17,8 @@ public class CascadingTriggerContextDiscoveryStrategy : ITriggerContextDiscovery new EventId(1, "Discovered"), "Discovered changes: {changes} for {name}. Iteration ({iteration}/{maxCascadingCycles})"); - readonly string _name; - readonly bool _skipDetectedChanges; - - public CascadingTriggerContextDiscoveryStrategy(string name, bool skipDetectedChanges) - { - _name = name ?? throw new ArgumentNullException(nameof(name)); - _skipDetectedChanges = skipDetectedChanges; - } + readonly string _name = name ?? throw new ArgumentNullException(nameof(name)); + readonly bool _skipDetectedChanges = skipDetectedChanges; public IEnumerable> Discover(TriggerSessionConfiguration configuration, TriggerContextTracker tracker, ILogger logger) { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs index 725c135..571dcd8 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs @@ -1,7 +1,4 @@ using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; namespace EntityFrameworkCore.Triggered.Internal.Descriptors { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs index 28d3d53..1c02947 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs @@ -1,7 +1,5 @@ using System; using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; namespace EntityFrameworkCore.Triggered.Internal.Descriptors { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs index ec55868..5c517cc 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs @@ -1,7 +1,5 @@ using System; using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; namespace EntityFrameworkCore.Triggered.Internal.Descriptors { diff --git a/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs b/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs index 744b7df..1bc8268 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs @@ -1,12 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; namespace EntityFrameworkCore.Triggered.Internal { public sealed class EntityBagStateManager { - private readonly Dictionary> _resolvedBags = new(); + private readonly Dictionary> _resolvedBags = []; public IDictionary GetForEntity(object entity) { diff --git a/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs b/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs index 530e75a..b91e700 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs @@ -3,16 +3,10 @@ namespace EntityFrameworkCore.Triggered.Internal { - public sealed class HybridServiceProvider : IServiceProvider + public sealed class HybridServiceProvider(IServiceProvider serviceProvider, DbContext dbContext) : IServiceProvider { - readonly DbContext _dbContext; - readonly IServiceProvider _serviceProvider; - - public HybridServiceProvider(IServiceProvider serviceProvider, DbContext dbContext) - { - _serviceProvider = serviceProvider; - _dbContext = dbContext; - } + readonly DbContext _dbContext = dbContext; + readonly IServiceProvider _serviceProvider = serviceProvider; public object? GetService(Type serviceType) { diff --git a/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs b/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs index 38554c2..86526bc 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs @@ -1,5 +1,4 @@ using System; -using EntityFrameworkCore.Triggered.Internal.Descriptors; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs index 4997be3..938947b 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs @@ -5,19 +5,14 @@ namespace EntityFrameworkCore.Triggered.Internal { - public class NonCascadingTriggerContextDiscoveryStrategy : ITriggerContextDiscoveryStrategy + public class NonCascadingTriggerContextDiscoveryStrategy(string name) : ITriggerContextDiscoveryStrategy { readonly static Action _changesDetected = LoggerMessage.Define( LogLevel.Debug, new EventId(1, "Discovered"), "Discovered changes: {changes} for {name}"); - readonly string _name; - - public NonCascadingTriggerContextDiscoveryStrategy(string name) - { - _name = name ?? throw new ArgumentNullException(nameof(name)); - } + readonly string _name = name ?? throw new ArgumentNullException(nameof(name)); public IEnumerable> Discover(TriggerSessionConfiguration configuration, TriggerContextTracker tracker, ILogger logger) { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs index 9a569e7..aed2a37 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs @@ -4,20 +4,13 @@ namespace EntityFrameworkCore.Triggered.Internal { - public readonly struct TriggerContextDescriptor + public readonly struct TriggerContextDescriptor(EntityEntry entityEntry, ChangeType changeType) { - static readonly ConcurrentDictionary> _cachedTriggerContextFactories = new(); + readonly static ConcurrentDictionary> _cachedTriggerContextFactories = new(); - readonly EntityEntry _entityEntry; - readonly ChangeType _changeType; - readonly PropertyValues? _originalValues; - - public TriggerContextDescriptor(EntityEntry entityEntry, ChangeType changeType) - { - _entityEntry = entityEntry; - _changeType = changeType; - _originalValues = entityEntry.OriginalValues.Clone(); - } + readonly EntityEntry _entityEntry = entityEntry; + readonly ChangeType _changeType = changeType; + readonly PropertyValues? _originalValues = entityEntry.OriginalValues.Clone(); public ChangeType ChangeType => _changeType; public object Entity => _entityEntry!.Entity; @@ -37,7 +30,7 @@ public object GetTriggerContext(EntityBagStateManager entityBagStateManager) var entityType = entityEntry.Entity.GetType(); var triggerContextFactory = _cachedTriggerContextFactories.GetOrAdd(entityType, entityType => - (Func)typeof(TriggerContextFactory<>).MakeGenericType(entityType) + (Func)typeof(TriggerContextFactory<>).MakeGenericType(entityType) !.GetMethod(nameof(TriggerContextFactory.Activate)) !.CreateDelegate(typeof(Func))); diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs index b9cca85..8f3e9e3 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs @@ -1,7 +1,6 @@ using System; using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.ChangeTracking; -using Microsoft.Extensions.DependencyInjection; namespace EntityFrameworkCore.Triggered.Internal { @@ -19,7 +18,7 @@ public static class TriggerContextFactory return Expression.Lambda>>( Expression.New( - typeof(TriggerContext<>).MakeGenericType(typeof(TEntityType)).GetConstructor(new[] { typeof(EntityEntry), typeof(PropertyValues), typeof(ChangeType), typeof(EntityBagStateManager) })!, + typeof(TriggerContext<>).MakeGenericType(typeof(TEntityType)).GetConstructor([typeof(EntityEntry), typeof(PropertyValues), typeof(ChangeType), typeof(EntityBagStateManager)])!, entityEntryParamExpression, originalValuesParamExpression, changeTypeParamExpression, diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs index 21bebef..547782b 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs @@ -6,20 +6,14 @@ namespace EntityFrameworkCore.Triggered.Internal { - public sealed class TriggerContextTracker + public sealed class TriggerContextTracker(ChangeTracker changeTracker, ICascadeStrategy cascadingStrategy) { - readonly ChangeTracker _changeTracker; - readonly ICascadeStrategy _cascadingStrategy; + readonly ChangeTracker _changeTracker = changeTracker; + readonly ICascadeStrategy _cascadingStrategy = cascadingStrategy; List? _discoveredChanges; List? _capturedChangeIndexes; - public TriggerContextTracker(ChangeTracker changeTracker, ICascadeStrategy cascadingStrategy) - { - _changeTracker = changeTracker; - _cascadingStrategy = cascadingStrategy; - } - static ChangeType? ResolveChangeType(EntityEntry entry) => entry.State switch { EntityState.Added => ChangeType.Added, EntityState.Modified => ChangeType.Modified, @@ -117,10 +111,7 @@ public void CaptureChanges() var changesCount = _discoveredChanges.Count; if (changesCount > 0) { - if (_capturedChangeIndexes == null) - { - _capturedChangeIndexes = new List(changesCount); // assuming all will be captured - } + _capturedChangeIndexes ??= new List(changesCount); // assuming all will be captured for (var changeIndex = 0; changeIndex < changesCount; changeIndex++) { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs index 80671bd..1cec7a8 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs @@ -7,15 +7,9 @@ public sealed class TriggerDescriptorComparer : IComparer, IC { public int Compare(TriggerDescriptor? x, TriggerDescriptor? y) { - if (x is null) - { - throw new ArgumentNullException(nameof(x)); - } + ArgumentNullException.ThrowIfNull(x); - if (y is null) - { - throw new ArgumentNullException(nameof(y)); - } + ArgumentNullException.ThrowIfNull(y); return x.Priority - y.Priority; } @@ -23,15 +17,9 @@ public int Compare(TriggerDescriptor? x, TriggerDescriptor? y) public int Compare(AsyncTriggerDescriptor? x, AsyncTriggerDescriptor? y) { - if (x is null) - { - throw new ArgumentNullException(nameof(x)); - } + ArgumentNullException.ThrowIfNull(x); - if (y is null) - { - throw new ArgumentNullException(nameof(y)); - } + ArgumentNullException.ThrowIfNull(y); return x.Priority - y.Priority; } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs index 10092e6..a4d5ca6 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs @@ -8,22 +8,15 @@ namespace EntityFrameworkCore.Triggered.Internal { - public sealed class TriggerDiscoveryService : ITriggerDiscoveryService, IResettableService + public sealed class TriggerDiscoveryService(ITriggerServiceProviderAccessor triggerServiceProviderAccessor, ITriggerTypeRegistryService triggerTypeRegistryService, TriggerFactory triggerFactory) : ITriggerDiscoveryService, IResettableService { readonly static TriggerDescriptorComparer _triggerDescriptorComparer = new(); - readonly ITriggerServiceProviderAccessor _triggerServiceProviderAccessor; - readonly ITriggerTypeRegistryService _triggerTypeRegistryService; - readonly TriggerFactory _triggerFactory; + readonly ITriggerServiceProviderAccessor _triggerServiceProviderAccessor = triggerServiceProviderAccessor; + readonly ITriggerTypeRegistryService _triggerTypeRegistryService = triggerTypeRegistryService ?? throw new ArgumentNullException(nameof(triggerTypeRegistryService)); + readonly TriggerFactory _triggerFactory = triggerFactory; IServiceProvider? _serviceProvider; - public TriggerDiscoveryService(ITriggerServiceProviderAccessor triggerServiceProviderAccessor, ITriggerTypeRegistryService triggerTypeRegistryService, TriggerFactory triggerFactory) - { - _triggerServiceProviderAccessor = triggerServiceProviderAccessor; - _triggerTypeRegistryService = triggerTypeRegistryService ?? throw new ArgumentNullException(nameof(triggerTypeRegistryService)); - _triggerFactory = triggerFactory; - } - public IEnumerable DiscoverTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) { var registry = _triggerTypeRegistryService.ResolveRegistry(openTriggerType, entityType, triggerTypeDescriptorFactory); @@ -31,7 +24,7 @@ public IEnumerable DiscoverTriggers(Type openTriggerType, Typ var triggerTypeDescriptors = registry.GetTriggerTypeDescriptors(); if (triggerTypeDescriptors.Length == 0) { - return Enumerable.Empty(); + return []; } else { @@ -42,10 +35,7 @@ public IEnumerable DiscoverTriggers(Type openTriggerType, Typ var triggers = _triggerFactory.Resolve(ServiceProvider, triggerTypeDescriptor.TriggerType); foreach (var trigger in triggers) { - if (triggerDescriptors == null) - { - triggerDescriptors = new List(); - } + triggerDescriptors ??= []; if (trigger != null) { @@ -56,7 +46,7 @@ public IEnumerable DiscoverTriggers(Type openTriggerType, Typ if (triggerDescriptors == null) { - return Enumerable.Empty(); + return []; } else { @@ -73,7 +63,7 @@ public IEnumerable DiscoverAsyncTriggers(Type openTrigge var triggerTypeDescriptors = registry.GetTriggerTypeDescriptors(); if (triggerTypeDescriptors.Length == 0) { - return Enumerable.Empty(); + return []; } else { @@ -84,10 +74,7 @@ public IEnumerable DiscoverAsyncTriggers(Type openTrigge var triggers = _triggerFactory.Resolve(ServiceProvider, triggerTypeDescriptor.TriggerType); foreach (var trigger in triggers) { - if (triggerDescriptors == null) - { - triggerDescriptors = new List(); - } + triggerDescriptors ??= []; if (trigger != null) { @@ -98,7 +85,7 @@ public IEnumerable DiscoverAsyncTriggers(Type openTrigge if (triggerDescriptors == null) { - return Enumerable.Empty(); + return []; } else { @@ -129,20 +116,14 @@ public IServiceProvider ServiceProvider { get { - if (_serviceProvider == null) - { - _serviceProvider = _triggerServiceProviderAccessor.GetTriggerServiceProvider(); - } + _serviceProvider ??= _triggerServiceProviderAccessor.GetTriggerServiceProvider(); return _serviceProvider; } set => _serviceProvider = value; } - public void ResetState() - { - _serviceProvider = null; - } + public void ResetState() => _serviceProvider = null; public Task ResetStateAsync(CancellationToken cancellationToken = default) { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs index d24c0b8..3c10da6 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs @@ -6,15 +6,10 @@ namespace EntityFrameworkCore.Triggered.Internal { - public sealed class TriggerFactory + public sealed class TriggerFactory(IServiceProvider internalServiceProvider) { - static readonly ConcurrentDictionary _instanceFactoryTypeCache = new(); - readonly IServiceProvider _internalServiceProvider; - - public TriggerFactory(IServiceProvider internalServiceProvider) - { - _internalServiceProvider = internalServiceProvider; - } + readonly static ConcurrentDictionary _instanceFactoryTypeCache = new(); + readonly IServiceProvider _internalServiceProvider = internalServiceProvider; public IEnumerable Resolve(IServiceProvider serviceProvider, Type triggerType) { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs index 53c4c36..4845c41 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs @@ -17,16 +17,11 @@ public interface ITriggerInstanceFactory : ITriggerInstanceFac } - public sealed class TriggerInstanceFactory : ITriggerInstanceFactory + public sealed class TriggerInstanceFactory(object? instance) : ITriggerInstanceFactory { static ObjectFactory? _internalFactory; - object? _instance; - - public TriggerInstanceFactory(object? instance) - { - _instance = instance; - } + object? _instance = instance; public object Create(IServiceProvider serviceProvider) { @@ -35,19 +30,13 @@ public object Create(IServiceProvider serviceProvider) return _instance; } - if (_internalFactory is null) - { - _internalFactory = ActivatorUtilities.CreateFactory(typeof(TTriggerType), Array.Empty()); - } + _internalFactory ??= ActivatorUtilities.CreateFactory(typeof(TTriggerType), []); _instance = _internalFactory(serviceProvider, null); return _instance; } - public void ResetState() - { - _instance = null; - } + public void ResetState() => _instance = null; public Task ResetStateAsync(CancellationToken cancellationToken = default) { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs index 3b2e446..e8600bc 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs @@ -164,7 +164,7 @@ public async ValueTask SavedChangesAsync(SaveChangesCompletedEventData even await _triggerSession.RaiseAfterSaveCompletedAsyncTriggers(cancellationToken).ConfigureAwait(false); DelistTriggerSession(eventData); - + return result; } @@ -185,10 +185,10 @@ public async Task SaveChangesFailedAsync(DbContextErrorEventData eventData, Canc _triggerSession.RaiseAfterSaveFailedStartingTriggers(eventData.Exception); await _triggerSession.RaiseAfterSaveFailedStartingAsyncTriggers(eventData.Exception, cancellationToken).ConfigureAwait(false); - + _triggerSession.RaiseAfterSaveFailedTriggers(eventData.Exception); await _triggerSession.RaiseAfterSaveFailedAsyncTriggers(eventData.Exception, cancellationToken).ConfigureAwait(false); - + _triggerSession.RaiseAfterSaveFailedCompletedTriggers(eventData.Exception); await _triggerSession.RaiseAfterSaveFailedCompletedAsyncTriggers(eventData.Exception, cancellationToken).ConfigureAwait(false); diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs index f77de74..42b0149 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -16,7 +15,7 @@ public static Action GetWeakDelegate(Type triggerType, Type enti var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetWeakDelegateHelper), BindingFlags.Static | BindingFlags.NonPublic); var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); - return (Action)constructedHelper.Invoke(null, new object[] { method })!; + return (Action)constructedHelper.Invoke(null, [method])!; } public static Action GetWeakDelegateWithException(Type triggerType, Type entityType, MethodInfo method) @@ -26,7 +25,7 @@ public static Action GetWeakDelegate(Type triggerType, Type enti var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetWeakDelegateHelperWithException), BindingFlags.Static | BindingFlags.NonPublic); var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); - return (Action)constructedHelper.Invoke(null, new object[] { method })!; + return (Action)constructedHelper.Invoke(null, [method])!; } static Action GetWeakDelegateHelper(MethodInfo method) @@ -54,7 +53,7 @@ public static Func GetAsyncWeakDelegate var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetAsyncWeakDelegateHelper), BindingFlags.Static | BindingFlags.NonPublic); var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); - return (Func)constructedHelper.Invoke(null, new object[] { method })!; + return (Func)constructedHelper.Invoke(null, [method])!; } public static Func GetAsyncWeakDelegateWithException(Type triggerType, Type entityType, MethodInfo method) @@ -64,7 +63,7 @@ public static Func GetAsyncWeakDelegate var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetAsyncWeakDelegateHelperWithException), BindingFlags.Static | BindingFlags.NonPublic); var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); - return (Func)constructedHelper.Invoke(null, new object[] { method })!; + return (Func)constructedHelper.Invoke(null, [method])!; } static Func GetAsyncWeakDelegateHelper(MethodInfo method) diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs index c531dce..adfd6cb 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs @@ -2,23 +2,16 @@ using System.Collections.Generic; using System.Linq; using EntityFrameworkCore.Triggered.Infrastructure.Internal; -using EntityFrameworkCore.Triggered.Internal.Descriptors; namespace EntityFrameworkCore.Triggered.Internal { - public sealed class TriggerTypeRegistry + public sealed class TriggerTypeRegistry(Type entityType, Func triggerTypeDescriptorFactory) { - readonly Type _entityType; - readonly Func _triggerTypeDescriptorFactory; + readonly Type _entityType = entityType; + readonly Func _triggerTypeDescriptorFactory = triggerTypeDescriptorFactory; TTriggerTypeDescriptor[]? _resolvedDescriptors; - public TriggerTypeRegistry(Type entityType, Func triggerTypeDescriptorFactory) - { - _entityType = entityType; - _triggerTypeDescriptorFactory = triggerTypeDescriptorFactory; - } - IEnumerable GetEntityTypeHierarchy() { // Enumerable of the type hierarchy from base to concrete diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs index 4cf03c0..0032f82 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Concurrent; -using EntityFrameworkCore.Triggered.Internal.Descriptors; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs index 9fd774f..1d26349 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs @@ -5,18 +5,12 @@ namespace EntityFrameworkCore.Triggered.Internal { - public sealed class TriggeredDbContextFactory : IDbContextFactory + public sealed class TriggeredDbContextFactory(TFactory contextFactory, IServiceProvider serviceProvider) : IDbContextFactory where TContext : DbContext where TFactory : IDbContextFactory { - private readonly TFactory _contextFactory; - private readonly IServiceProvider _serviceProvider; - - public TriggeredDbContextFactory(TFactory contextFactory, IServiceProvider serviceProvider) - { - _contextFactory = contextFactory; - _serviceProvider = serviceProvider; - } + private readonly TFactory _contextFactory = contextFactory; + private readonly IServiceProvider _serviceProvider = serviceProvider; public TContext CreateDbContext() { @@ -32,18 +26,12 @@ public TContext CreateDbContext() return context; } } - - public sealed class TriggeredDbContextFactory : IDbContextFactory + + public sealed class TriggeredDbContextFactory(Func> contextFactoryFactory, IServiceProvider serviceProvider) : IDbContextFactory where TContext : DbContext { - readonly Func> _contextFactoryFactory; - readonly IServiceProvider _serviceProvider; - - public TriggeredDbContextFactory(Func> contextFactoryFactory, IServiceProvider serviceProvider) - { - _contextFactoryFactory = contextFactoryFactory; - _serviceProvider = serviceProvider; - } + readonly Func> _contextFactoryFactory = contextFactoryFactory; + readonly IServiceProvider _serviceProvider = serviceProvider; public TContext CreateDbContext() { @@ -52,10 +40,7 @@ public TContext CreateDbContext() Debug.Assert(context is not null); var applicationTriggerServiceProviderAccessor = context.GetService(); - if (applicationTriggerServiceProviderAccessor != null) - { - applicationTriggerServiceProviderAccessor.SetTriggerServiceProvider(new HybridServiceProvider(_serviceProvider, context)); - } + applicationTriggerServiceProviderAccessor?.SetTriggerServiceProvider(new HybridServiceProvider(_serviceProvider, context)); return context; } diff --git a/src/EntityFrameworkCore.Triggered/TriggerContext.cs b/src/EntityFrameworkCore.Triggered/TriggerContext.cs index 667e59f..9d35244 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerContext.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerContext.cs @@ -4,24 +4,16 @@ namespace EntityFrameworkCore.Triggered { - public class TriggerContext : ITriggerContext + public class TriggerContext(EntityEntry entityEntry, PropertyValues? originalValues, ChangeType changeType, EntityBagStateManager entityBagStateManager) : ITriggerContext where TEntity : class { - readonly EntityEntry _entityEntry; - readonly ChangeType _type; - readonly PropertyValues? _originalValues; - readonly EntityBagStateManager _entityBagStateManager; + readonly EntityEntry _entityEntry = entityEntry; + readonly ChangeType _type = changeType; + readonly PropertyValues? _originalValues = originalValues; + readonly EntityBagStateManager _entityBagStateManager = entityBagStateManager; TEntity? _unmodifiedEntity; - public TriggerContext(EntityEntry entityEntry, PropertyValues? originalValues, ChangeType changeType, EntityBagStateManager entityBagStateManager) - { - _entityEntry = entityEntry; - _originalValues = originalValues; - _type = changeType; - _entityBagStateManager = entityBagStateManager; - } - public ChangeType ChangeType => _type; public TEntity Entity => (TEntity)_entityEntry.Entity; public TEntity? UnmodifiedEntity diff --git a/src/EntityFrameworkCore.Triggered/TriggerService.cs b/src/EntityFrameworkCore.Triggered/TriggerService.cs index e8208c8..cba4ac5 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerService.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerService.cs @@ -26,7 +26,7 @@ public TriggerService(ITriggerDiscoveryService triggerDiscoveryService, ICascade _cascadingStrategy = cascadingStrategy ?? throw new ArgumentNullException(nameof(cascadingStrategy)); _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); _defaultConfiguration = new TriggerSessionConfiguration(false, triggerOptions.Value.MaxCascadeCycles); - + Configuration = _defaultConfiguration; } @@ -43,10 +43,7 @@ public ITriggerSession CreateSession(DbContext context, IServiceProvider? servic public ITriggerSession CreateSession(DbContext context, TriggerSessionConfiguration configuration, IServiceProvider? serviceProvider) { - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var triggerContextTracker = new TriggerContextTracker(context.ChangeTracker, _cascadingStrategy); diff --git a/src/EntityFrameworkCore.Triggered/TriggerSession.cs b/src/EntityFrameworkCore.Triggered/TriggerSession.cs index 70e9ba4..bff8d08 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerSession.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerSession.cs @@ -10,33 +10,24 @@ namespace EntityFrameworkCore.Triggered { - public class TriggerSession : ITriggerSession + public class TriggerSession(ITriggerService triggerService, TriggerSessionConfiguration configuration, ITriggerDiscoveryService triggerDiscoveryService, TriggerContextTracker tracker, ILogger logger) : ITriggerSession { static ITriggerContextDiscoveryStrategy? _beforeSaveTriggerContextDiscoveryStrategy; static ITriggerContextDiscoveryStrategy? _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges; // To satisfy RaiseBeforeSaveTrigger's overload static ITriggerContextDiscoveryStrategy? _afterSaveTriggerContextDiscoveryStrategy; static ITriggerContextDiscoveryStrategy? _afterSaveFailedTriggerContextDiscoveryStrategy; - readonly ITriggerService _triggerService; - readonly TriggerSessionConfiguration _configuration; - readonly ITriggerDiscoveryService _triggerDiscoveryService; - readonly TriggerContextTracker _tracker; - readonly ILogger _logger; + readonly ITriggerService _triggerService = triggerService ?? throw new ArgumentNullException(nameof(triggerService)); + readonly TriggerSessionConfiguration _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + readonly ITriggerDiscoveryService _triggerDiscoveryService = triggerDiscoveryService ?? throw new ArgumentNullException(nameof(triggerDiscoveryService)); + readonly TriggerContextTracker _tracker = tracker ?? throw new ArgumentNullException(nameof(tracker)); + readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger)); readonly EntityBagStateManager _entityBagStateManager = new(); bool _raiseBeforeSaveTriggersCalled; bool _raiseBeforeSaveAsyncTriggersCalled; - public TriggerSession(ITriggerService triggerService, TriggerSessionConfiguration configuration, ITriggerDiscoveryService triggerDiscoveryService, TriggerContextTracker tracker, ILogger logger) - { - _triggerService = triggerService ?? throw new ArgumentNullException(nameof(triggerService)); - _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); - _triggerDiscoveryService = triggerDiscoveryService ?? throw new ArgumentNullException(nameof(triggerDiscoveryService)); - _tracker = tracker ?? throw new ArgumentNullException(nameof(tracker)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } - public TriggerContextTracker Tracker => _tracker; public ITriggerDiscoveryService DiscoveryService => _triggerDiscoveryService; @@ -47,10 +38,7 @@ public void DiscoverChanges() public void RaiseTriggers(Type openTriggerType, Exception? exception, ITriggerContextDiscoveryStrategy triggerContextDiscoveryStrategy, Func triggerTypeDescriptorFactory) { - if (triggerContextDiscoveryStrategy == null) - { - throw new ArgumentNullException(nameof(triggerContextDiscoveryStrategy)); - } + ArgumentNullException.ThrowIfNull(triggerContextDiscoveryStrategy); if (_configuration.Disabled) { @@ -68,10 +56,7 @@ public void RaiseTriggers(Type openTriggerType, Exception? exception, ITriggerCo foreach (var triggerDescriptor in triggerDescriptors) { - if (triggerInvocations == null) - { - triggerInvocations = new List<(TriggerContextDescriptor triggerContextDescriptor, TriggerDescriptor triggerDescriptor)>(); - } + triggerInvocations ??= []; triggerInvocations.Add((triggerContextDescriptor, triggerDescriptor)); } @@ -100,10 +85,7 @@ public void RaiseTriggers(Type openTriggerType, Exception? exception, ITriggerCo public async Task RaiseAsyncTriggers(Type openTriggerType, Exception? exception, ITriggerContextDiscoveryStrategy triggerContextDiscoveryStrategy, Func triggerTypeDescriptorFactory, CancellationToken cancellationToken) { - if (triggerContextDiscoveryStrategy == null) - { - throw new ArgumentNullException(nameof(triggerContextDiscoveryStrategy)); - } + ArgumentNullException.ThrowIfNull(triggerContextDiscoveryStrategy); if (_configuration.Disabled) { @@ -123,10 +105,7 @@ public async Task RaiseAsyncTriggers(Type openTriggerType, Exception? exception, foreach (var triggerDescriptor in triggerDescriptors) { - if (triggerInvocations == null) - { - triggerInvocations = new List<(TriggerContextDescriptor triggerContextDescriptor, AsyncTriggerDescriptor triggerDescriptor)>(); - } + triggerInvocations ??= []; triggerInvocations.Add((triggerContextDescriptor, triggerDescriptor)); } @@ -186,19 +165,13 @@ public void RaiseBeforeSaveTriggers(bool skipDetectedChanges) if (skipDetectedChanges) { - if (_beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges == null) - { - _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges = new CascadingTriggerContextDiscoveryStrategy("BeforeSave", true); - } + _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", true); strategy = _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges; } else { - if (_beforeSaveTriggerContextDiscoveryStrategy == null) - { - _beforeSaveTriggerContextDiscoveryStrategy = new CascadingTriggerContextDiscoveryStrategy("BeforeSave", false); - } + _beforeSaveTriggerContextDiscoveryStrategy ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", false); strategy = _beforeSaveTriggerContextDiscoveryStrategy; } @@ -218,19 +191,13 @@ public Task RaiseBeforeSaveAsyncTriggers(bool skipDetectedChanges, CancellationT if (skipDetectedChanges) { - if (_beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges == null) - { - _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges = new CascadingTriggerContextDiscoveryStrategy("BeforeSave", true); - } + _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", true); strategy = _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges; } else { - if (_beforeSaveTriggerContextDiscoveryStrategy == null) - { - _beforeSaveTriggerContextDiscoveryStrategy = new CascadingTriggerContextDiscoveryStrategy("BeforeSave", false); - } + _beforeSaveTriggerContextDiscoveryStrategy ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", false); strategy = _beforeSaveTriggerContextDiscoveryStrategy; } @@ -283,20 +250,14 @@ public async Task RaiseAfterSaveStartingAsyncTriggers(CancellationToken cancella public void RaiseAfterSaveTriggers() { - if (_afterSaveTriggerContextDiscoveryStrategy == null) - { - _afterSaveTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("AfterSave"); - } + _afterSaveTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSave"); RaiseTriggers(typeof(IAfterSaveTrigger<>), null, _afterSaveTriggerContextDiscoveryStrategy, entityType => new AfterSaveTriggerDescriptor(entityType)); } public Task RaiseAfterSaveAsyncTriggers(CancellationToken cancellationToken = default) { - if (_afterSaveTriggerContextDiscoveryStrategy == null) - { - _afterSaveTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("AfterSave"); - } + _afterSaveTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSave"); return RaiseAsyncTriggers(typeof(IAfterSaveAsyncTrigger<>), null, _afterSaveTriggerContextDiscoveryStrategy, entityType => new AfterSaveAsyncTriggerDescriptor(entityType), cancellationToken); } @@ -343,20 +304,14 @@ public async Task RaiseAfterSaveFailedStartingAsyncTriggers(Exception exception, public void RaiseAfterSaveFailedTriggers(Exception exception) { - if (_afterSaveFailedTriggerContextDiscoveryStrategy == null) - { - _afterSaveFailedTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("AfterSaveFailed"); - } + _afterSaveFailedTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSaveFailed"); RaiseTriggers(typeof(IAfterSaveFailedTrigger<>), exception, _afterSaveFailedTriggerContextDiscoveryStrategy, entityType => new AfterSaveFailedTriggerDescriptor(entityType)); } public Task RaiseAfterSaveFailedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) { - if (_afterSaveFailedTriggerContextDiscoveryStrategy == null) - { - _afterSaveFailedTriggerContextDiscoveryStrategy = new NonCascadingTriggerContextDiscoveryStrategy("AfterSaveFailed"); - } + _afterSaveFailedTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSaveFailed"); return RaiseAsyncTriggers(typeof(IAfterSaveFailedAsyncTrigger<>), exception, _afterSaveFailedTriggerContextDiscoveryStrategy, entityType => new AfterSaveFailedAsyncTriggerDescriptor(entityType), cancellationToken); } diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs index 1cc2418..f84a310 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; namespace EntityFrameworkCore.Triggered.Extensions.Tests { diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs index 67abe00..9055c90 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs @@ -30,13 +30,8 @@ public class TestModel public int Id { get; set; } } - public class TestDbContext : DbContext + public class TestDbContext(DbContextOptions options) : DbContext(options) { - public TestDbContext(DbContextOptions options) - : base(options) - { - } - public DbSet TestModels { get; set; } } @@ -128,7 +123,7 @@ public Task SaveChanges_ExplicitlyAddedTriggerThroughDI_RaisesAllTriggerTypes() => SaveChanges_TriggeredAddedThroughDI_Template(x => { x.AddTrigger(); x.AddTrigger(); - + return x; }); diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextExtensionsTests.cs index e506365..80e2aa2 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextExtensionsTests.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs index d939649..fc01615 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Linq; using EntityFrameworkCore.Triggered.Infrastructure; using EntityFrameworkCore.Triggered.Infrastructure.Internal; using Microsoft.EntityFrameworkCore; diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/ApplicationDbContext.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/ApplicationDbContext.cs index 2c329f7..9ce8a13 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/ApplicationDbContext.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/ApplicationDbContext.cs @@ -4,32 +4,21 @@ namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes { - public class ApplicationDbContext : DbContext + public class ApplicationDbContext(string databaseName) : DbContext { - readonly string _databaseName; + readonly string _databaseName = databaseName; - public ApplicationDbContext(string databaseName) - { - _databaseName = databaseName; - } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseInMemoryDatabase(_databaseName) .UseTriggers(triggerOptions => { triggerOptions.AddTrigger(); }); - } - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity() + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .HasOne(x => x.Parent) .WithMany(x => x.Children) .HasForeignKey(x => x.ParentId) .OnDelete(DeleteBehavior.Cascade); - } public DbSet Branches => Set(); } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs index 516fa1d..2239c50 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs @@ -4,14 +4,9 @@ namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Triggers { - public class SoftDelete : Trigger + public class SoftDelete(ApplicationDbContext applicationDbContext) : Trigger { - readonly ApplicationDbContext _applicationDbContext; - - public SoftDelete(ApplicationDbContext applicationDbContext) - { - _applicationDbContext = applicationDbContext; - } + readonly ApplicationDbContext _applicationDbContext = applicationDbContext; public override void BeforeSave(ITriggerContext context) { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/ApplicationDbContext.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/ApplicationDbContext.cs index f088c60..cab870b 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/ApplicationDbContext.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/ApplicationDbContext.cs @@ -2,12 +2,8 @@ namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags { - public class ApplicationDbContext : DbContext + public class ApplicationDbContext(DbContextOptions options) : DbContext(options) { - public ApplicationDbContext(DbContextOptions options) : base(options) - { - } - public DbSet Users { get; set; } } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/EntityBagsTestScenario.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/EntityBagsTestScenario.cs index f3c1725..b89ab3c 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/EntityBagsTestScenario.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/EntityBagsTestScenario.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.EntityFrameworkCore; using ScenarioTests; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs index 2fa301f..684d474 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs @@ -1,22 +1,12 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers { - public class SoftDeleteTrigger : IBeforeSaveTrigger + public class SoftDeleteTrigger(ApplicationDbContext dbContext) : IBeforeSaveTrigger { public const string IsSoftDeleted = "SoftDeleteTrigger_IsSoftDeleted"; - readonly ApplicationDbContext _dbContext; - - public SoftDeleteTrigger(ApplicationDbContext dbContext) - { - _dbContext = dbContext; - } + readonly ApplicationDbContext _dbContext = dbContext; public void BeforeSave(ITriggerContext context) { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs index d83409e..8cf6739 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/ApplicationDbContext.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/ApplicationDbContext.cs index b2d0bd4..6a99aee 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/ApplicationDbContext.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/ApplicationDbContext.cs @@ -2,12 +2,8 @@ namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests { - public class ApplicationDbContext : DbContext + public class ApplicationDbContext(DbContextOptions options) : DbContext(options) { - public ApplicationDbContext(DbContextOptions options) : base(options) - { - } - public DbSet Users { get; set; } } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/ScopedTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/ScopedTrigger.cs index 7995686..5c8a9f9 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/ScopedTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/ScopedTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users +namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users { class ScopedTrigger : IBeforeSaveTrigger { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/SingletonTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/SingletonTrigger.cs index 9303c63..cb0f9e9 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/SingletonTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/SingletonTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users +namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users { class SingletonTrigger : IBeforeSaveTrigger diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/TransientTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/TransientTrigger.cs index 28c8b38..6fdb342 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/TransientTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/TransientTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users +namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users { class TransientTrigger : IBeforeSaveTrigger { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/ApplicationDbContext.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/ApplicationDbContext.cs index 5928bd2..b764892 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/ApplicationDbContext.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/ApplicationDbContext.cs @@ -3,14 +3,9 @@ namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore { - public class ApplicationDbContext : DbContext + public class ApplicationDbContext(string databaseName) : DbContext { - readonly string _databaseName; - - public ApplicationDbContext(string databaseName) - { - _databaseName = databaseName; - } + readonly string _databaseName = databaseName; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs index 6ca482a..00e552c 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs @@ -4,14 +4,9 @@ namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Triggers.Users { - public class SoftDeleteUsers : Trigger + public class SoftDeleteUsers(ApplicationDbContext applicationDbContext) : Trigger { - readonly ApplicationDbContext _applicationDbContext; - - public SoftDeleteUsers(ApplicationDbContext applicationDbContext) - { - _applicationDbContext = applicationDbContext; - } + readonly ApplicationDbContext _applicationDbContext = applicationDbContext; public override void BeforeSave(ITriggerContext context) { diff --git a/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs b/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs index 5148a43..b81c04b 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs @@ -18,16 +18,9 @@ public class TestModel public string Name { get; set; } } -#pragma warning disable CS0618 // Type or member is obsolete - class TestDbContext : DbContext -#pragma warning restore CS0618 // Type or member is obsolete + class TestDbContext(bool stubService = true) : DbContext { - readonly bool _stubService; - - public TestDbContext(bool stubService = true) - { - _stubService = stubService; - } + readonly bool _stubService = stubService; public TriggerStub TriggerStub { get; } = new TriggerStub(); diff --git a/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs index 28ecf55..4da8318 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs @@ -1,5 +1,4 @@ using System; -using System.Threading; using System.Threading.Tasks; using EntityFrameworkCore.Triggered.Extensions; using Microsoft.EntityFrameworkCore; @@ -17,10 +16,7 @@ class SampleTrigger : IBeforeSaveTrigger { public int BeforeSaveCalls { get; set; } - public void BeforeSave(ITriggerContext context) - { - BeforeSaveCalls += 1; - } + public void BeforeSave(ITriggerContext context) => BeforeSaveCalls += 1; } class TestDbContext : DbContext diff --git a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs index 819cb48..f3cde62 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs @@ -12,22 +12,14 @@ namespace EntityFrameworkCore.Triggered.Tests.Infrastructure public class ServiceCollectionExtensionsTests { class TestModel { public int Id { get; set; } } -#pragma warning disable CS0618 // Type or member is obsolete - class TestDbContext : DbContext -#pragma warning restore CS0618 // Type or member is obsolete + class TestDbContext(DbContextOptions options) : DbContext(options) { public DbSet TestModels { get; set; } - public TestDbContext(DbContextOptions options) : base(options) - { - } } - class TestDbContextFactory : DbContextFactory + class TestDbContextFactory(IServiceProvider serviceProvider, DbContextOptions options, IDbContextFactorySource factorySource) : DbContextFactory(serviceProvider, options, factorySource) { - public TestDbContextFactory(IServiceProvider serviceProvider, DbContextOptions options, IDbContextFactorySource factorySource) : base(serviceProvider, options, factorySource) - { - } } [Fact] diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs index 9d31043..51d4ca5 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs @@ -1,7 +1,5 @@ using System; using System.Linq; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveTriggerDescriptorTests.cs index b00b1fc..b7583b9 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveTriggerDescriptorTests.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveTriggerDescriptorTests.cs index 4e756fd..cb31da8 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveTriggerDescriptorTests.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/EntityBagStateManagerTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/EntityBagStateManagerTests.cs index d64b8ce..1045f32 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/EntityBagStateManagerTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/EntityBagStateManagerTests.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using Xunit; namespace EntityFrameworkCore.Triggered.Tests.Internal diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs index 0970aab..2d1e770 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs @@ -1,6 +1,4 @@ using System; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs index d5b2556..5410f7a 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs @@ -10,14 +10,9 @@ namespace EntityFrameworkCore.Triggered.Tests.Internal { public class TriggerDiscoveryServiceTests { - class TriggerServiceProviderAccessor : ITriggerServiceProviderAccessor + class TriggerServiceProviderAccessor(IServiceProvider serviceProvider) : ITriggerServiceProviderAccessor { - readonly IServiceProvider _serviceProvider; - - public TriggerServiceProviderAccessor(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } + readonly IServiceProvider _serviceProvider = serviceProvider; public IServiceProvider GetTriggerServiceProvider() => _serviceProvider; } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs index 1318799..1862681 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs @@ -1,7 +1,5 @@ using System; using System.Linq; -using System.Threading; -using System.Threading.Tasks; using EntityFrameworkCore.Triggered.Internal; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -18,27 +16,17 @@ class SampleTrigger : IBeforeSaveTrigger public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); } - class SampleTrigger2 : IBeforeSaveTrigger + class SampleTrigger2(TriggerFactory triggerFactory) : IBeforeSaveTrigger { - public SampleTrigger2(TriggerFactory triggerFactory) - { - TriggerFactory = triggerFactory; - } - - public TriggerFactory TriggerFactory { get; } + public TriggerFactory TriggerFactory { get; } = triggerFactory; public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); } - class SampleTrigger3 : IBeforeSaveTrigger + class SampleTrigger3(TDbContext dbContext) : IBeforeSaveTrigger where TDbContext : DbContext { - public SampleTrigger3(TDbContext dbContext) - { - DbContext = dbContext; - } - - public TDbContext DbContext { get; } + public TDbContext DbContext { get; } = dbContext; public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerInstanceFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerInstanceFactoryTests.cs index bf64c53..2b0b731 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerInstanceFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerInstanceFactoryTests.cs @@ -8,15 +8,16 @@ namespace EntityFrameworkCore.Triggered.Tests.Internal { public partial class TriggerInstanceFactoryTests { - class SampleDbContext : DbContext + class SampleDbContext(DbContextOptions options) : DbContext(options) { - public SampleDbContext(DbContextOptions options) : base(options) - { - } } class SampleTrigger1 { } - class SampleTrigger2 { public SampleTrigger2(SampleDbContext sampleDbContext) { } } +#pragma warning disable CS9113 // Parameter is unread. + class SampleTrigger2(TriggerInstanceFactoryTests.SampleDbContext sampleDbContext) +#pragma warning restore CS9113 // Parameter is unread. + { + } [Scenario] public void TriggerInstanceFactoriesBehaviorTests(ScenarioContext scenario) diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs index dcc84af..2522978 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs @@ -18,17 +18,9 @@ public class TestModel public string Name { get; set; } } -#pragma warning disable CS0618 // Type or member is obsolete - class TestDbContext : DbContext -#pragma warning restore CS0618 // Type or member is obsolete + class TestDbContext(bool stubService = true) : DbContext { - readonly bool _stubService; - - public TestDbContext(bool stubService = true) - { - _stubService = stubService; - } - + readonly bool _stubService = stubService; public SqliteConnection UseSqlLiteConnection; public TriggerStub TriggerStub { get; } = new TriggerStub(); diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs index 37892d6..1bf1773 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs @@ -4,15 +4,10 @@ namespace EntityFrameworkCore.Triggered.Tests.Stubs { - public class BeforeSaveDelegatingTrigger : IBeforeSaveTrigger, IBeforeSaveAsyncTrigger + public class BeforeSaveDelegatingTrigger(Func, CancellationToken, Task> handler) : IBeforeSaveTrigger, IBeforeSaveAsyncTrigger where TEntity : class { - readonly Func, CancellationToken, Task> _handler; - - public BeforeSaveDelegatingTrigger(Func, CancellationToken, Task> handler) - { - _handler = handler; - } + readonly Func, CancellationToken, Task> _handler = handler; public void BeforeSave(ITriggerContext context) => _handler(context, default).Wait(); public Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => _handler(context, cancellationToken); diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/EventDefinitionBaseStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/EventDefinitionBaseStub.cs index 2108872..d4ecde3 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/EventDefinitionBaseStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/EventDefinitionBaseStub.cs @@ -1,20 +1,15 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics.Internal; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.Extensions.Logging; namespace EntityFrameworkCore.Triggered.Tests.Stubs { - public class EventDefinitionBaseStub : EventDefinitionBase + public class EventDefinitionBaseStub(ILoggingOptions loggingOptions, EventId eventId, LogLevel level, string eventIdCode) : EventDefinitionBase(loggingOptions, eventId, level, eventIdCode) { public EventDefinitionBaseStub() : this(new LoggingOptions(), new EventId(), default, "test") { } - - public EventDefinitionBaseStub(ILoggingOptions loggingOptions, EventId eventId, LogLevel level, string eventIdCode) : base(loggingOptions, eventId, level, eventIdCode) - { - } } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs index afeac67..5c20568 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs @@ -10,14 +10,13 @@ namespace EntityFrameworkCore.Triggered.Tests.Stubs public class TriggerDiscoveryServiceStub : ITriggerDiscoveryService { public IEnumerable DiscoverAsyncTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) - => Enumerable.Empty(); + => []; - public IEnumerable DiscoverTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) - => Enumerable.Empty(); + public IEnumerable DiscoverTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) + => []; public IEnumerable DiscoverTriggers() - => Enumerable.Empty(); - + => []; public IServiceProvider ServiceProvider { get; set; } = new ServiceCollection().BuildServiceProvider(); } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs index e2b4842..bec9237 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs @@ -2,14 +2,9 @@ namespace EntityFrameworkCore.Triggered.Tests.Stubs { - public class TriggerServiceProviderAccessorStub : ITriggerServiceProviderAccessor + public class TriggerServiceProviderAccessorStub(IServiceProvider serviceProvider) : ITriggerServiceProviderAccessor { - readonly IServiceProvider _serviceProvider; - - public TriggerServiceProviderAccessorStub(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } + readonly IServiceProvider _serviceProvider = serviceProvider; public IServiceProvider GetTriggerServiceProvider() => _serviceProvider; } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs index 3675d91..446f392 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs @@ -6,41 +6,35 @@ namespace EntityFrameworkCore.Triggered.Tests.Stubs { public class TriggerSessionStub : ITriggerSession { - public int RaiseBeforeSaveStartingTriggersCalls; - public int RaiseBeforeSaveStartingAsyncTriggersCalls; - public int RaiseBeforeSaveTriggersCalls; - public int RaiseBeforeSaveAsyncTriggersCalls; - public int RaiseBeforeSaveCompletingTriggersCalls; - public int RaiseBeforeSaveCompletingAsyncTriggersCalls; - public int RaiseAfterSaveStartingTriggersCalls; - public int RaiseAfterSaveStartingAsyncTriggersCalls; - public int RaiseAfterSaveTriggersCalls; - public int RaiseAfterSaveAsyncTriggersCalls; - public int RaiseAfterSaveCompletedTriggersCalls; - public int RaiseAfterSaveCompletedAsyncTriggersCalls; - public int RaiseAfterSaveFailedStartingTriggersCalls; - public int RaiseAfterSaveFailedStartingAsyncTriggersCalls; - public int RaiseAfterSaveFailedTriggersCalls; - public int RaiseAfterSaveFailedAsyncTriggersCalls; - public int RaiseAfterSaveFailedCompletedTriggersCalls; - public int RaiseAfterSaveFailedCompletedAsyncTriggersCalls; - public int CaptureDiscoveredChangesCalls; - public int DiscoverChangesCalls; - public int DisposeCalls; + public int RaiseBeforeSaveStartingTriggersCalls { get; set; } + public int RaiseBeforeSaveStartingAsyncTriggersCalls { get; set; } + public int RaiseBeforeSaveTriggersCalls { get; set; } + public int RaiseBeforeSaveAsyncTriggersCalls { get; set; } + public int RaiseBeforeSaveCompletingTriggersCalls { get; set; } + public int RaiseBeforeSaveCompletingAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveStartingTriggersCalls { get; set; } + public int RaiseAfterSaveStartingAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveTriggersCalls { get; set; } + public int RaiseAfterSaveAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveCompletedTriggersCalls { get; set; } + public int RaiseAfterSaveCompletedAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveFailedStartingTriggersCalls { get; set; } + public int RaiseAfterSaveFailedStartingAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveFailedTriggersCalls { get; set; } + public int RaiseAfterSaveFailedAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveFailedCompletedTriggersCalls { get; set; } + public int RaiseAfterSaveFailedCompletedAsyncTriggersCalls { get; set; } + public int CaptureDiscoveredChangesCalls { get; set; } + public int DiscoverChangesCalls { get; set; } + public int DisposeCalls { get; set; } public void CaptureDiscoveredChanges() => CaptureDiscoveredChangesCalls += 1; public void DiscoverChanges() => DiscoverChangesCalls += 1; - public void Dispose() - { - DisposeCalls += 1; - } + public void Dispose() => DisposeCalls += 1; - public void RaiseAfterSaveFailedStartingTriggers(Exception exception) - { - RaiseAfterSaveFailedStartingTriggersCalls += 1; - } + public void RaiseAfterSaveFailedStartingTriggers(Exception exception) => RaiseAfterSaveFailedStartingTriggersCalls += 1; public Task RaiseAfterSaveFailedStartingAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) { @@ -48,10 +42,7 @@ public Task RaiseAfterSaveFailedStartingAsyncTriggers(Exception exception, Cance return Task.CompletedTask; } - public void RaiseAfterSaveFailedTriggers(Exception exception) - { - RaiseAfterSaveFailedTriggersCalls += 1; - } + public void RaiseAfterSaveFailedTriggers(Exception exception) => RaiseAfterSaveFailedTriggersCalls += 1; public Task RaiseAfterSaveFailedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) { @@ -59,10 +50,7 @@ public Task RaiseAfterSaveFailedAsyncTriggers(Exception exception, CancellationT return Task.CompletedTask; } - public void RaiseAfterSaveFailedCompletedTriggers(Exception exception) - { - RaiseAfterSaveFailedCompletedTriggersCalls += 1; - } + public void RaiseAfterSaveFailedCompletedTriggers(Exception exception) => RaiseAfterSaveFailedCompletedTriggersCalls += 1; public Task RaiseAfterSaveFailedCompletedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) { @@ -70,10 +58,7 @@ public Task RaiseAfterSaveFailedCompletedAsyncTriggers(Exception exception, Canc return Task.CompletedTask; } - public void RaiseBeforeSaveStartingTriggers() - { - RaiseBeforeSaveStartingTriggersCalls += 1; - } + public void RaiseBeforeSaveStartingTriggers() => RaiseBeforeSaveStartingTriggersCalls += 1; public Task RaiseBeforeSaveStartingAsyncTriggers(CancellationToken cancellationToken = default) { @@ -81,10 +66,7 @@ public Task RaiseBeforeSaveStartingAsyncTriggers(CancellationToken cancellationT return Task.CompletedTask; } - public void RaiseBeforeSaveTriggers() - { - RaiseBeforeSaveTriggersCalls += 1; - } + public void RaiseBeforeSaveTriggers() => RaiseBeforeSaveTriggersCalls += 1; public Task RaiseBeforeSaveAsyncTriggers(CancellationToken cancellationToken = default) { @@ -92,10 +74,7 @@ public Task RaiseBeforeSaveAsyncTriggers(CancellationToken cancellationToken = d return Task.CompletedTask; } - public void RaiseBeforeSaveCompletedTriggers() - { - RaiseBeforeSaveCompletingTriggersCalls += 1; - } + public void RaiseBeforeSaveCompletedTriggers() => RaiseBeforeSaveCompletingTriggersCalls += 1; public Task RaiseBeforeSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default) { @@ -103,10 +82,7 @@ public Task RaiseBeforeSaveCompletedAsyncTriggers(CancellationToken cancellation return Task.CompletedTask; } - public void RaiseAfterSaveStartingTriggers() - { - RaiseAfterSaveStartingTriggersCalls += 1; - } + public void RaiseAfterSaveStartingTriggers() => RaiseAfterSaveStartingTriggersCalls += 1; public Task RaiseAfterSaveStartingAsyncTriggers(CancellationToken cancellationToken = default) { @@ -114,10 +90,7 @@ public Task RaiseAfterSaveStartingAsyncTriggers(CancellationToken cancellationTo return Task.CompletedTask; } - public void RaiseAfterSaveTriggers() - { - RaiseAfterSaveTriggersCalls += 1; - } + public void RaiseAfterSaveTriggers() => RaiseAfterSaveTriggersCalls += 1; public Task RaiseAfterSaveAsyncTriggers(CancellationToken cancellationToken = default) { @@ -125,10 +98,7 @@ public Task RaiseAfterSaveAsyncTriggers(CancellationToken cancellationToken = de return Task.CompletedTask; } - public void RaiseAfterSaveCompletedTriggers() - { - RaiseAfterSaveCompletedTriggersCalls += 1; - } + public void RaiseAfterSaveCompletedTriggers() => RaiseAfterSaveCompletedTriggersCalls += 1; public Task RaiseAfterSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default) { @@ -136,10 +106,7 @@ public Task RaiseAfterSaveCompletedAsyncTriggers(CancellationToken cancellationT return Task.CompletedTask; } - public void RaiseBeforeSaveTriggers(bool skipDetectedChanges = false) - { - RaiseBeforeSaveTriggersCalls += 1; - } + public void RaiseBeforeSaveTriggers(bool skipDetectedChanges = false) => RaiseBeforeSaveTriggersCalls += 1; public Task RaiseBeforeSaveAsyncTriggers(bool skipDetectedChanges = false, CancellationToken cancellationToken = default) { diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs index 9c5276a..1c5cabc 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs @@ -5,7 +5,7 @@ namespace EntityFrameworkCore.Triggered.Tests.Stubs { - public class TriggerStub : + public class TriggerStub : IBeforeSaveTrigger, IBeforeSaveAsyncTrigger, IAfterSaveTrigger, @@ -15,10 +15,10 @@ public class TriggerStub : ITriggerPriority where TEntity : class { - public ICollection> BeforeSaveInvocations { get; } = new List>(); - public ICollection> BeforeSaveAsyncInvocations { get; } = new List>(); - public ICollection> AfterSaveInvocations { get; } = new List>(); - public ICollection> AfterSaveAsyncInvocations { get; } = new List>(); + public ICollection> BeforeSaveInvocations { get; } = []; + public ICollection> BeforeSaveAsyncInvocations { get; } = []; + public ICollection> AfterSaveInvocations { get; } = []; + public ICollection> AfterSaveAsyncInvocations { get; } = []; public ICollection<(ITriggerContext context, Exception exception)> AfterSaveFailedInvocations { get; } = new List<(ITriggerContext, Exception)>(); public ICollection<(ITriggerContext context, Exception exception)> AfterSaveFailedAsyncInvocations { get; } = new List<(ITriggerContext, Exception)>(); diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs index 03a826d..7952333 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs @@ -11,16 +11,8 @@ public class TriggerServiceApplicationDependenciesTests { class TestModel { public int Id { get; set; } } -#pragma warning disable CS0618 // Type or member is obsolete - class TestDbContext : DbContext -#pragma warning restore CS0618 // Type or member is obsolete + class TestDbContext(DbContextOptions options) : DbContext(options) { - public TestDbContext(DbContextOptions options) - : base(options) - { - - } - public DbSet TestModels { get; set; } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs index c2fe5e4..cbb2e34 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; @@ -19,29 +14,15 @@ public class TestModel public string Name { get; set; } } - class TestTrigger : IBeforeSaveTrigger + class TestTrigger(TriggeredDbContextFactoryTests.TestDbContext testDbContext) : IBeforeSaveTrigger { - readonly TestDbContext _testDbContext; + readonly TestDbContext _testDbContext = testDbContext; - public TestTrigger(TestDbContext testDbContext) - { - _testDbContext = testDbContext; - } - - public void BeforeSave(ITriggerContext context) - { - _testDbContext.TriggerRaised = true; - } + public void BeforeSave(ITriggerContext context) => _testDbContext.TriggerRaised = true; } - class TestDbContext : DbContext + class TestDbContext(DbContextOptions options) : DbContext(options) { - public TestDbContext(DbContextOptions options) - : base(options) - { - - } - public DbSet TestModels { get; set; } public bool TriggerRaised { get; set; } = false; diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterCommitTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterCommitTriggerDescriptorTests.cs index 4f39181..406a283 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterCommitTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterCommitTriggerDescriptorTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Transactions.Internal; +using EntityFrameworkCore.Triggered.Transactions.Internal; using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterRollbackTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterRollbackTriggerDescriptorTests.cs index 525021a..8f508b5 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterRollbackTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterRollbackTriggerDescriptorTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Transactions.Internal; +using EntityFrameworkCore.Triggered.Transactions.Internal; using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeCommitTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeCommitTriggerDescriptorTests.cs index 11d6478..43fefcb 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeCommitTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeCommitTriggerDescriptorTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Transactions.Internal; +using EntityFrameworkCore.Triggered.Transactions.Internal; using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeRollbackTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeRollbackTriggerDescriptorTests.cs index 130f032..a2b9a0c 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeRollbackTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeRollbackTriggerDescriptorTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Transactions.Internal; +using EntityFrameworkCore.Triggered.Transactions.Internal; using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs index 17b1632..7848b4d 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs @@ -5,7 +5,7 @@ namespace EntityFrameworkCore.Triggered.Transactions.Tests.Stubs { - public class TriggerStub : + public class TriggerStub : IBeforeCommitTrigger, IBeforeCommitAsyncTrigger, IAfterCommitTrigger, @@ -34,19 +34,16 @@ public class TriggerStub : public int AfterCommitCompletedInvocationsCount { get; set; } public int AfterCommitCompletedAsyncInvocationsCount { get; set; } - public ICollection> BeforeCommitInvocations { get; } = new List>(); - public ICollection> BeforeCommitAsyncInvocations { get; } = new List>(); - public ICollection> AfterCommitInvocations { get; } = new List>(); - public ICollection> AfterCommitAsyncInvocations { get; } = new List>(); - public ICollection> BeforeRollbackInvocations { get; } = new List>(); - public ICollection> BeforeRollbackAsyncInvocations { get; } = new List>(); - public ICollection> AfterRollbackInvocations { get; } = new List>(); - public ICollection> AfterRollbackAsyncInvocations { get; } = new List>(); + public ICollection> BeforeCommitInvocations { get; } = []; + public ICollection> BeforeCommitAsyncInvocations { get; } = []; + public ICollection> AfterCommitInvocations { get; } = []; + public ICollection> AfterCommitAsyncInvocations { get; } = []; + public ICollection> BeforeRollbackInvocations { get; } = []; + public ICollection> BeforeRollbackAsyncInvocations { get; } = []; + public ICollection> AfterRollbackInvocations { get; } = []; + public ICollection> AfterRollbackAsyncInvocations { get; } = []; - public void BeforeCommitStarting() - { - BeforeCommitStartingInvocationsCount++; - } + public void BeforeCommitStarting() => BeforeCommitStartingInvocationsCount++; public Task BeforeCommitStartingAsync(CancellationToken cancellationToken) { @@ -54,10 +51,7 @@ public Task BeforeCommitStartingAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - public void BeforeCommitCompleted() - { - BeforeCommitCompletedInvocationsCount++; - } + public void BeforeCommitCompleted() => BeforeCommitCompletedInvocationsCount++; public Task BeforeCommitCompletedAsync(CancellationToken cancellationToken) { @@ -65,10 +59,7 @@ public Task BeforeCommitCompletedAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - public void AfterCommitStarting() - { - AfterCommitStartingInvocationsCount++; - } + public void AfterCommitStarting() => AfterCommitStartingInvocationsCount++; public Task AfterCommitStartingAsync(CancellationToken cancellationToken) { @@ -76,10 +67,7 @@ public Task AfterCommitStartingAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - public void AfterCommitCompleted() - { - AfterCommitCompletedInvocationsCount++; - } + public void AfterCommitCompleted() => AfterCommitCompletedInvocationsCount++; public Task AfterCommitCompletedAsync(CancellationToken cancellationToken) { @@ -87,10 +75,7 @@ public Task AfterCommitCompletedAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - public void BeforeCommit(ITriggerContext context) - { - BeforeCommitInvocations.Add(context); - } + public void BeforeCommit(ITriggerContext context) => BeforeCommitInvocations.Add(context); public Task BeforeCommitAsync(ITriggerContext context, CancellationToken cancellationToken) { @@ -98,10 +83,7 @@ public Task BeforeCommitAsync(ITriggerContext context, CancellationToke return Task.CompletedTask; } - public void AfterCommit(ITriggerContext context) - { - AfterCommitInvocations.Add(context); - } + public void AfterCommit(ITriggerContext context) => AfterCommitInvocations.Add(context); public Task AfterCommitAsync(ITriggerContext context, CancellationToken cancellationToken) { @@ -109,10 +91,7 @@ public Task AfterCommitAsync(ITriggerContext context, CancellationToken return Task.CompletedTask; } - public void BeforeRollback(ITriggerContext context) - { - BeforeRollbackInvocations.Add(context); - } + public void BeforeRollback(ITriggerContext context) => BeforeRollbackInvocations.Add(context); public Task BeforeRollbackAsync(ITriggerContext context, CancellationToken cancellationToken) { @@ -120,10 +99,7 @@ public Task BeforeRollbackAsync(ITriggerContext context, CancellationTo return Task.CompletedTask; } - public void AfterRollback(ITriggerContext context) - { - AfterRollbackInvocations.Add(context); - } + public void AfterRollback(ITriggerContext context) => AfterRollbackInvocations.Add(context); public Task AfterRollbackAsync(ITriggerContext context, CancellationToken cancellationToken) { From 0d84ea8e12c7fce94950104733b974c30ffd228f Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 18:05:46 +0000 Subject: [PATCH 07/16] Updated github actions --- .github/workflows/build.yml | 14 ++------------ .github/workflows/release.yml | 2 +- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 545c966..6f91052 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -21,23 +21,13 @@ jobs: strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] - version: [1, 2, 3] - include: - - version: 1 - configuration: ReleaseV1 - - version: 2 - configuration: ReleaseV2 - - version: 3 - configuration: Release runs-on: ${{ matrix.os }} - steps: - uses: actions/checkout@v2 - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: - dotnet-version: 6.0.x - include-prerelease: True + dotnet-version: 8.0.x - name: Install dependencies run: dotnet restore EntityFrameworkCore.Triggered.sln -p:Configuration=${{ matrix.configuration }} - name: Build @@ -66,7 +56,7 @@ jobs: - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: - dotnet-version: 6.0.x + dotnet-version: 8.0.x include-prerelease: True - name: Install dependencies run: dotnet restore EntityFrameworkCore.Triggered.Samples.slnf diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3bde8a6..76f50a8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -25,7 +25,7 @@ jobs: - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: - dotnet-version: 6.0.x + dotnet-version: 8.0.x - name: Create Release NuGet package run: | arrTag=(${GITHUB_REF//\// }) From 9435c7c5167070ca4bd1c586413259067c456655 Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 18:31:38 +0000 Subject: [PATCH 08/16] Simplified samples and more cleanup --- Directory.Build.props | 1 + .../ApplicationContext.cs | 3 +- .../EmbracingFeaturesBenchmarks.cs | 4 +- .../PlainOverheadBenchmarks.cs | 4 +- .../SetStudentRegistrationDateTrigger.cs | 4 +- .../SignStudentUpForMandatoryCourses.cs | 4 +- .../1 - HelloWorld/ApplicationDbContext.cs | 3 +- samples/1 - HelloWorld/Program.cs | 27 ++---- .../Triggers/StudentAssignRegistrationDate.cs | 3 +- .../2 - PrimarySchool/ApplicationDbContext.cs | 3 +- samples/2 - PrimarySchool/Program.cs | 84 ++++++++----------- .../StudentSignupToMandatoryCourses.cs | 3 +- .../3 - StudentManagerAspNetCore/Models.cs | 4 +- .../Pages/Audits/Index.cshtml.cs | 4 +- .../Pages/Courses/Create.cshtml.cs | 3 +- .../Pages/Courses/Delete.cshtml.cs | 3 +- .../Pages/Courses/Details.cshtml.cs | 3 +- .../Pages/Courses/Edit.cshtml.cs | 4 +- .../Pages/Courses/Index.cshtml.cs | 4 +- .../Pages/Error.cshtml.cs | 1 - .../Pages/Index.cshtml.cs | 1 - .../Pages/Students/Create.cshtml.cs | 3 +- .../Pages/Students/Delete.cshtml.cs | 3 +- .../Pages/Students/Details.cshtml.cs | 3 +- .../Pages/Students/Edit.cshtml.cs | 4 +- .../Pages/Students/Index.cshtml.cs | 4 +- .../3 - StudentManagerAspNetCore/Program.cs | 65 +++++++++++--- .../3 - StudentManagerAspNetCore/Startup.cs | 73 ---------------- .../Traits/ISoftDelete.cs | 4 +- .../Triggers/Courses/AutoSignupStudents.cs | 5 +- .../BlockRemovalWhenCourseIsMandatory.cs | 5 +- .../StudentCourses/SendWelcomingEmail.cs | 4 +- .../Students/AssignRegistrationDate.cs | 3 +- .../Students/SignupToMandatoryCourses.cs | 5 +- .../Traits/Audited/CreateAuditRecord.cs | 4 +- .../Traits/SoftDelete/EnsureSoftDelete.cs | 3 +- .../4 - BlazorTests/ApplicationDbContext.cs | 3 +- .../4 - BlazorTests/Data/WeatherForecast.cs | 2 - .../Data/WeatherForecastService.cs | 4 - samples/4 - BlazorTests/EventAggregator.cs | 4 +- samples/4 - BlazorTests/Pages/Error.cshtml.cs | 1 - samples/4 - BlazorTests/Program.cs | 55 +++++++++--- samples/4 - BlazorTests/Startup.cs | 63 -------------- .../Triggers/Counts/SetCreatedOn.cs | 3 +- .../IAfterSaveAsyncTrigger.cs | 5 +- .../IAfterSaveFailedAsyncTrigger.cs | 6 +- .../IAfterSaveFailedTrigger.cs | 4 +- .../IBeforeSaveAsyncTrigger.cs | 5 +- .../ITriggerContext.cs | 4 +- .../ITriggerSession.cs | 6 +- .../IAfterSaveCompletedAsyncTrigger.cs | 5 +- .../IAfterSaveFailedCompletedAsyncTrigger.cs | 6 +- .../IAfterSaveFailedCompletedTrigger.cs | 4 +- .../IAfterSaveFailedStartingAsyncTrigger.cs | 6 +- .../IAfterSaveFailedStartingTrigger.cs | 4 +- .../IAfterSaveStartingAsyncTrigger.cs | 5 +- .../IBeforeSaveCompletedAsyncTrigger.cs | 5 +- .../IBeforeSaveStartingAsyncTrigger.cs | 5 +- .../ServiceCollectionExtensions.cs | 4 +- .../Trigger.cs | 6 +- .../TriggerContextExtensions.cs | 3 +- ...TriggersContextOptionsBuilderExtensions.cs | 4 +- .../IAfterCommitAsyncTrigger.cs | 5 +- .../IAfterRollbackAsyncTrigger.cs | 5 +- .../IBeforeCommitAsyncTrigger.cs | 5 +- .../IBeforeRollbackAsyncTrigger.cs | 5 +- .../IAfterCommitCompletedAsyncTrigger.cs | 5 +- .../IAfterCommitStartingAsyncTrigger.cs | 5 +- .../IBeforeCommitCompletedAsyncTrigger.cs | 5 +- .../IBeforeCommitStartingAsyncTrigger.cs | 5 +- ...TriggersContextOptionsBuilderExtensions.cs | 3 +- .../AfterCommitAsyncTriggerDescriptor.cs | 5 +- .../Internal/AfterCommitTriggerDescriptor.cs | 3 +- .../AfterRollbackAsyncTriggerDescriptor.cs | 5 +- .../AfterRollbackTriggerDescriptor.cs | 3 +- .../BeforeCommitAsyncTriggerDescriptor.cs | 5 +- .../Internal/BeforeCommitTriggerDescriptor.cs | 3 +- .../BeforeRollbackAsyncTriggerDescriptor.cs | 5 +- .../BeforeRollbackTriggerDescriptor.cs | 3 +- .../TriggeredSessionExtensions.cs | 5 +- .../Extensions/DbContextExtensions.cs | 5 +- .../Extensions/ServiceCollectionExtensions.cs | 4 +- .../TriggersDbContextOptionsExtensions.cs | 3 +- .../ITriggerService.cs | 3 +- .../ITriggerServiceProviderAccessor.cs | 4 +- .../Internal/TriggersOptionExtension.cs | 5 +- .../Infrastructure/Internal/TypeHelpers.cs | 6 +- .../TriggersContextOptionsBuilder.cs | 3 +- ...plicationTriggerServiceProviderAccessor.cs | 5 +- .../Internal/AsyncTriggerDescriptor.cs | 5 +- ...ascadingTriggerContextDiscoveryStrategy.cs | 5 +- .../AfterSaveAsyncTriggerDescriptor.cs | 5 +- .../AfterSaveFailedAsyncTriggerDescriptor.cs | 6 +- .../AfterSaveFailedTriggerDescriptor.cs | 4 +- .../Descriptors/AfterSaveTriggerDescriptor.cs | 3 +- .../BeforeSaveAsyncTriggerDescriptor.cs | 5 +- .../BeforeSaveTriggerDescriptor.cs | 3 +- .../IAsyncTriggerTypeDescriptor.cs | 6 +- .../Descriptors/ITriggerTypeDescriptor.cs | 4 +- .../Internal/EntityStateBagManager.cs | 4 +- .../Internal/HybridServiceProvider.cs | 3 +- .../ITriggerContextDiscoveryStrategy.cs | 3 +- .../Internal/ITriggerDiscoveryService.cs | 4 +- .../Internal/ITriggerTypeRegistryService.cs | 4 +- ...ascadingTriggerContextDiscoveryStrategy.cs | 5 +- .../Internal/TriggerContextDescriptor.cs | 3 +- .../Internal/TriggerContextFactory.cs | 3 +- .../Internal/TriggerContextTracker.cs | 4 +- .../Internal/TriggerDescriptor.cs | 3 +- .../Internal/TriggerDescriptorComparer.cs | 5 +- .../Internal/TriggerDiscoveryService.cs | 7 +- .../Internal/TriggerFactory.cs | 5 +- .../Internal/TriggerInstanceFactory.cs | 5 +- .../TriggerSessionSaveChangesInterceptor.cs | 3 - .../Internal/TriggerTypeDescriptorHelpers.cs | 5 +- .../Internal/TriggerTypeRegistry.cs | 5 +- .../Internal/TriggerTypeRegistryService.cs | 3 +- .../Internal/TriggeredDbContextFactory.cs | 3 +- .../TriggerContext.cs | 3 +- .../TriggerService.cs | 5 +- .../TriggerSession.cs | 7 +- .../AbstractTrigger.cs | 4 +- .../SampleTrigger.cs | 5 +- .../SampleTriggerClone.cs | 5 +- .../ServiceCollectionExtensionsTests.cs | 6 +- ...gerContextOptionsBuilderExtensionsTests.cs | 3 +- .../CascadingSoftDeletes/Models/Branch.cs | 5 +- .../Triggers/SoftDelete.cs | 3 +- .../EntityBags/Triggers/SoftDeleteTrigger.cs | 4 +- .../Triggers/StampModifiedOnTrigger.cs | 4 +- .../EntityBags/User.cs | 4 +- .../SampleStore/Models/User.cs | 4 +- .../SampleStore/TestScenario.cs | 3 +- .../Triggers/Users/SoftDeleteUsers.cs | 3 +- .../EFCore5DbContextTests.cs | 4 +- .../Extensions/DbContextExtensionTests.cs | 4 +- .../ServiceCollectionExtensionsTests.cs | 3 +- .../TriggersContextOptionsBuilderTests.cs | 3 +- ...ingTriggerContextDiscoveryStrategyTests.cs | 4 +- .../AfterSaveAsyncTriggerDescriptorTests.cs | 3 +- ...erSaveFailedAsyncTriggerDescriptorTests.cs | 5 +- .../AfterSaveFailedTriggerDescriptorTests.cs | 4 +- .../BeforeSaveAsyncTriggerDescriptorTests.cs | 3 +- ...ingTriggerContextDiscoveryStrategyTests.cs | 4 +- .../Internal/TriggerContextFactoryTests.cs | 3 +- .../Internal/TriggerContextTrackerTests.cs | 4 +- .../Internal/TriggerDescriptorTests.cs | 3 +- .../Internal/TriggerDiscoveryServiceTests.cs | 4 +- .../Internal/TriggerFactoryTests.cs | 4 +- ...iggerSessionSaveChangesInterceptorTests.cs | 4 +- .../TriggerTypeDescriptorHelpersTests.cs | 3 +- .../Internal/TriggerTypeRegistryTests.cs | 3 +- .../Internal/TypeHelpersTests.cs | 5 +- .../Stubs/BeforeSaveDelegatingTrigger.cs | 6 +- .../Stubs/OptionsSnapshotStub.cs | 3 +- .../Stubs/TriggerContextStub.cs | 4 +- .../Stubs/TriggerDiscoveryServiceStub.cs | 5 +- .../TriggerServiceProviderAccessorStub.cs | 4 +- .../Stubs/TriggerServiceStub.cs | 3 +- .../Stubs/TriggerSessionStub.cs | 6 +- .../Stubs/TriggerStub.cs | 7 +- ...ggerServiceApplicationDependenciesTests.cs | 3 +- .../TriggerSessionTests.cs | 6 +- .../TriggeredDbContextFactoryTests.cs | 3 +- .../Stubs/TriggerContextStub.cs | 4 +- .../Stubs/TriggerStub.cs | 5 +- .../TriggeredDbContextTests.cs | 3 +- .../TriggeredSessionExtensionsTests.cs | 4 +- 168 files changed, 296 insertions(+), 729 deletions(-) delete mode 100644 samples/3 - StudentManagerAspNetCore/Startup.cs delete mode 100644 samples/4 - BlazorTests/Startup.cs diff --git a/Directory.Build.props b/Directory.Build.props index 4ba8668..2a84635 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,6 +7,7 @@ enable true README.md + enable diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs index 7a7948c..55449c8 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; namespace EntityFrameworkCore.Triggered.Benchmarks diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs index 3c92432..ff08434 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Attributes; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs index 9c0ca0f..4ca303c 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Attributes; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs index 4203f97..90584e3 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers +namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers { public class SetStudentRegistrationDateTrigger : IBeforeSaveTrigger { diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs index 3e755a8..6f8ec68 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs @@ -1,6 +1,4 @@ -using System.Linq; - -namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers +namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers { public class SignStudentUpForMandatoryCourses(TriggeredApplicationContext applicationContext) : IBeforeSaveTrigger { diff --git a/samples/1 - HelloWorld/ApplicationDbContext.cs b/samples/1 - HelloWorld/ApplicationDbContext.cs index c359253..635195b 100644 --- a/samples/1 - HelloWorld/ApplicationDbContext.cs +++ b/samples/1 - HelloWorld/ApplicationDbContext.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; namespace PrimarySchool { diff --git a/samples/1 - HelloWorld/Program.cs b/samples/1 - HelloWorld/Program.cs index 152b9c5..7785646 100644 --- a/samples/1 - HelloWorld/Program.cs +++ b/samples/1 - HelloWorld/Program.cs @@ -1,22 +1,13 @@ -using System; +using PrimarySchool; -namespace PrimarySchool -{ - class Program - { - static void Main(string[] args) - { - var applicationContext = new ApplicationDbContext(); +var applicationContext = new ApplicationDbContext(); - applicationContext.Students.Add(new Student { - Id = 1, - DisplayName = "Joe" - }); +applicationContext.Students.Add(new Student { + Id = 1, + DisplayName = "Joe" +}); - applicationContext.SaveChanges(); +applicationContext.SaveChanges(); - var joe = applicationContext.Students.Find(1); - Console.WriteLine($"Joe was registered on: {joe.RegistrationDate}"); - } - } -} +var joe = applicationContext.Students.Find(1); +Console.WriteLine($"Joe was registered on: {joe.RegistrationDate}"); diff --git a/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs b/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs index 47f3566..64cd27c 100644 --- a/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs +++ b/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; namespace PrimarySchool.Triggers { diff --git a/samples/2 - PrimarySchool/ApplicationDbContext.cs b/samples/2 - PrimarySchool/ApplicationDbContext.cs index cc883f2..3d344e3 100644 --- a/samples/2 - PrimarySchool/ApplicationDbContext.cs +++ b/samples/2 - PrimarySchool/ApplicationDbContext.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; namespace PrimarySchool { diff --git a/samples/2 - PrimarySchool/Program.cs b/samples/2 - PrimarySchool/Program.cs index 964df0a..727d9f6 100644 --- a/samples/2 - PrimarySchool/Program.cs +++ b/samples/2 - PrimarySchool/Program.cs @@ -1,56 +1,46 @@ -using System; -using System.Linq; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace PrimarySchool -{ - class Program - { - static void Main(string[] args) - { - var serviceProvider = new ServiceCollection() - .AddDbContext(options => { - options - .UseInMemoryDatabase("PrimarySchool") - .UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(); - }); - }) - .BuildServiceProvider(); - - var serviceScope = serviceProvider.CreateScope(); - var applicationContext = serviceScope.ServiceProvider.GetRequiredService(); - - applicationContext.Courses.Add(new Course { - Id = 1, - DisplayName = "Mathematics", - IsMandatory = true +using PrimarySchool; +using PrimarySchool.Triggers; + +var serviceProvider = new ServiceCollection() + .AddDbContext(options => { + options + .UseInMemoryDatabase("PrimarySchool") + .UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(); }); + }) + .BuildServiceProvider(); - applicationContext.Courses.Add(new Course { - Id = 2, - DisplayName = "Art", - IsMandatory = false - }); +var serviceScope = serviceProvider.CreateScope(); +var applicationContext = serviceScope.ServiceProvider.GetRequiredService(); - applicationContext.SaveChanges(); +applicationContext.Courses.Add(new Course { + Id = 1, + DisplayName = "Mathematics", + IsMandatory = true +}); - applicationContext.Students.Add(new Student { - Id = 1, - DisplayName = "Joe" - }); +applicationContext.Courses.Add(new Course { + Id = 2, + DisplayName = "Art", + IsMandatory = false +}); - applicationContext.SaveChanges(); +applicationContext.SaveChanges(); - var joesCourses = applicationContext.StudentCourses - .Where(x => x.StudentId == 1) - .Select(x => x.Course.DisplayName); +applicationContext.Students.Add(new Student { + Id = 1, + DisplayName = "Joe" +}); - foreach (var course in joesCourses) - { - Console.WriteLine($"Joe is registered for course {course}"); - } - } - } +applicationContext.SaveChanges(); + +var joesCourses = applicationContext.StudentCourses + .Where(x => x.StudentId == 1) + .Select(x => x.Course.DisplayName); + +foreach (var course in joesCourses) +{ + Console.WriteLine($"Joe is registered for course {course}"); } diff --git a/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs b/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs index 7b01187..781e65b 100644 --- a/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs +++ b/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs @@ -1,5 +1,4 @@ -using System.Linq; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; namespace PrimarySchool.Triggers { diff --git a/samples/3 - StudentManagerAspNetCore/Models.cs b/samples/3 - StudentManagerAspNetCore/Models.cs index 3c6911c..1211a03 100644 --- a/samples/3 - StudentManagerAspNetCore/Models.cs +++ b/samples/3 - StudentManagerAspNetCore/Models.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using StudentManager.Traits; +using StudentManager.Traits; namespace StudentManager { diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs index 074b15c..2817fb7 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; namespace StudentManager.Pages diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs index c48c76f..b034423 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace StudentManager.Pages.Courses diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs index 88d8709..c0084b2 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs index 13245ed..dac2a66 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs index e9e4cc8..71879cf 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs index 50023c2..b2c2add 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; namespace StudentManager.Pages.Courses diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs index 4dc505b..73e3031 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs @@ -1,7 +1,6 @@ using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -using Microsoft.Extensions.Logging; namespace StudentManager.Pages { diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs index dcae617..8a7bdda 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc.RazorPages; -using Microsoft.Extensions.Logging; namespace StudentManager.Pages { diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs index d6a1ee9..8844a34 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace StudentManager.Pages.Students diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs index 9147cb0..410945f 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs index 5d5eae1..ab0e003 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs index bfdbb01..ca983e2 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs index 49beeeb..0fac5ed 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; namespace StudentManager.Pages.Students diff --git a/samples/3 - StudentManagerAspNetCore/Program.cs b/samples/3 - StudentManagerAspNetCore/Program.cs index de55a78..f18b109 100644 --- a/samples/3 - StudentManagerAspNetCore/Program.cs +++ b/samples/3 - StudentManagerAspNetCore/Program.cs @@ -1,16 +1,55 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; +using Microsoft.EntityFrameworkCore; +using StudentManager; +using StudentManager.Services; -namespace StudentManager +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddRazorPages(); +builder.Services.AddSingleton(); + +builder.Services.AddDbContext(options => { + options + .UseSqlite("Data source=test.db") + .UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(); + triggerOptions.AddTrigger(); + triggerOptions.AddTrigger(); + triggerOptions.AddTrigger(); + triggerOptions.AddTrigger(); + triggerOptions.AddTrigger(); + triggerOptions.AddTrigger(); + + options.EnableSensitiveDataLogging(); + }); +}); + +builder.Services.AddHttpContextAccessor(); + +var app = builder.Build(); + +app.Start(); + +using (var serviceScope = app.Services.GetRequiredService().CreateScope()) { - public class Program - { - public static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => { - webBuilder.UseStartup(); - }); - } + var context = serviceScope.ServiceProvider.GetRequiredService(); + context.Database.EnsureCreated(); } + +// Configure the HTTP request pipeline. +if (!app.Environment.IsDevelopment()) +{ + app.UseExceptionHandler("/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); +} + +app.UseHttpsRedirection(); +app.UseStaticFiles(); + +app.UseRouting(); + +app.UseAuthorization(); + +app.MapRazorPages(); + +app.Run(); \ No newline at end of file diff --git a/samples/3 - StudentManagerAspNetCore/Startup.cs b/samples/3 - StudentManagerAspNetCore/Startup.cs deleted file mode 100644 index b4e6bb4..0000000 --- a/samples/3 - StudentManagerAspNetCore/Startup.cs +++ /dev/null @@ -1,73 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using StudentManager.Services; - -namespace StudentManager -{ - public class Startup(IConfiguration configuration) - { - public IConfiguration Configuration { get; } = configuration; - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddRazorPages(); - - services.AddSingleton(); - - services - .AddDbContext(options => { - options - .UseSqlite("Data source=test.db") - .UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(); - triggerOptions.AddTrigger(); - triggerOptions.AddTrigger(); - triggerOptions.AddTrigger(); - triggerOptions.AddTrigger(); - triggerOptions.AddTrigger(); - triggerOptions.AddTrigger(); - }); - - options.EnableSensitiveDataLogging(true); - }) - .AddHttpContextAccessor(); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - using (var serviceScope = app.ApplicationServices.GetService().CreateScope()) - { - var context = serviceScope.ServiceProvider.GetRequiredService(); - context.Database.EnsureCreated(); - } - - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseExceptionHandler("/Error"); - // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. - app.UseHsts(); - } - - app.UseHttpsRedirection(); - app.UseStaticFiles(); - - app.UseRouting(); - - app.UseAuthorization(); - - app.UseEndpoints(endpoints => { - endpoints.MapRazorPages(); - }); - } - } -} diff --git a/samples/3 - StudentManagerAspNetCore/Traits/ISoftDelete.cs b/samples/3 - StudentManagerAspNetCore/Traits/ISoftDelete.cs index a88a41a..5349046 100644 --- a/samples/3 - StudentManagerAspNetCore/Traits/ISoftDelete.cs +++ b/samples/3 - StudentManagerAspNetCore/Traits/ISoftDelete.cs @@ -1,6 +1,4 @@ -using System; - -namespace StudentManager.Traits +namespace StudentManager.Traits { public interface ISoftDelete { diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs index b748525..f7d2437 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs @@ -1,7 +1,4 @@ -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; using Microsoft.EntityFrameworkCore; namespace StudentManager.Triggers.Courses diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs index 8ff1e24..5acb418 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; namespace StudentManager.Triggers.StudentCourses { diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs index 44cadfb..abdb60f 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs @@ -1,6 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; using StudentManager.Services; namespace StudentManager.Triggers.StudentCourses diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs index 8f11fe4..5026224 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; namespace StudentManager.Triggers.Students { diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs index 4c79120..223ee18 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs @@ -1,7 +1,4 @@ -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; using Microsoft.EntityFrameworkCore; namespace StudentManager.Triggers.Students diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs index 24c31df..846f9b3 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using System.Text; +using System.Text; using EntityFrameworkCore.Triggered; using StudentManager.Traits; diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs index 243554f..ec67469 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; using StudentManager.Traits; namespace StudentManager.Triggers.Traits.SoftDelete diff --git a/samples/4 - BlazorTests/ApplicationDbContext.cs b/samples/4 - BlazorTests/ApplicationDbContext.cs index e9d7586..4674726 100644 --- a/samples/4 - BlazorTests/ApplicationDbContext.cs +++ b/samples/4 - BlazorTests/ApplicationDbContext.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; namespace BlazorTests { diff --git a/samples/4 - BlazorTests/Data/WeatherForecast.cs b/samples/4 - BlazorTests/Data/WeatherForecast.cs index 801f2e8..8fc963e 100644 --- a/samples/4 - BlazorTests/Data/WeatherForecast.cs +++ b/samples/4 - BlazorTests/Data/WeatherForecast.cs @@ -1,5 +1,3 @@ -using System; - namespace BlazorTests.Data { public class WeatherForecast diff --git a/samples/4 - BlazorTests/Data/WeatherForecastService.cs b/samples/4 - BlazorTests/Data/WeatherForecastService.cs index 7eec729..79006ed 100644 --- a/samples/4 - BlazorTests/Data/WeatherForecastService.cs +++ b/samples/4 - BlazorTests/Data/WeatherForecastService.cs @@ -1,7 +1,3 @@ -using System; -using System.Linq; -using System.Threading.Tasks; - namespace BlazorTests.Data { public class WeatherForecastService diff --git a/samples/4 - BlazorTests/EventAggregator.cs b/samples/4 - BlazorTests/EventAggregator.cs index 8995130..c7c8a94 100644 --- a/samples/4 - BlazorTests/EventAggregator.cs +++ b/samples/4 - BlazorTests/EventAggregator.cs @@ -1,6 +1,4 @@ -using System; - -namespace BlazorTests +namespace BlazorTests { /// /// This is NOT a production ready EventAggregator and only used for demo purposes diff --git a/samples/4 - BlazorTests/Pages/Error.cshtml.cs b/samples/4 - BlazorTests/Pages/Error.cshtml.cs index 2aaf9e8..087fda3 100644 --- a/samples/4 - BlazorTests/Pages/Error.cshtml.cs +++ b/samples/4 - BlazorTests/Pages/Error.cshtml.cs @@ -1,7 +1,6 @@ using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -using Microsoft.Extensions.Logging; namespace BlazorTests.Pages { diff --git a/samples/4 - BlazorTests/Program.cs b/samples/4 - BlazorTests/Program.cs index 3d9dd45..e0ecf62 100644 --- a/samples/4 - BlazorTests/Program.cs +++ b/samples/4 - BlazorTests/Program.cs @@ -1,16 +1,45 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; +using BlazorTests; +using Microsoft.EntityFrameworkCore; -namespace BlazorTests +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddRazorPages(); +builder.Services.AddServerSideBlazor(); +builder.Services.AddSingleton(); + +builder.Services.AddTriggeredDbContextFactory(options => { + options + .UseSqlite("Data source=test.db") + .UseTriggers(triggerOptions => { + triggerOptions.AddAssemblyTriggers(); + }); +}); + +var app = builder.Build(); + +using (var serviceScope = app.Services.GetRequiredService().CreateScope()) +{ + var contextFactory = serviceScope.ServiceProvider.GetRequiredService>(); + using var context = contextFactory.CreateDbContext(); + context.Database.EnsureCreated(); +} + +// Configure the HTTP request pipeline. +if (!app.Environment.IsDevelopment()) { - public class Program - { - public static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => { - webBuilder.UseStartup(); - }); - } + app.UseExceptionHandler("/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); } + +app.UseHttpsRedirection(); +app.UseStaticFiles(); + +app.UseRouting(); + +app.UseAuthorization(); + +app.MapRazorPages(); + +app.Run(); \ No newline at end of file diff --git a/samples/4 - BlazorTests/Startup.cs b/samples/4 - BlazorTests/Startup.cs deleted file mode 100644 index ee79abf..0000000 --- a/samples/4 - BlazorTests/Startup.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace BlazorTests -{ - public class Startup(IConfiguration configuration) - { - public IConfiguration Configuration { get; } = configuration; - - // This method gets called by the runtime. Use this method to add services to the container. - // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 - public void ConfigureServices(IServiceCollection services) - { - services.AddRazorPages(); - services.AddServerSideBlazor(); - services.AddSingleton(); - - services.AddTriggeredDbContextFactory(options => { - options - .UseSqlite("Data source=test.db") - .UseTriggers(triggerOptions => { - triggerOptions.AddAssemblyTriggers(); - }); - }); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - using (var serviceScope = app.ApplicationServices.GetService().CreateScope()) - { - var contextFactory = serviceScope.ServiceProvider.GetRequiredService>(); - using var context = contextFactory.CreateDbContext(); - context.Database.EnsureCreated(); - } - - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseExceptionHandler("/Error"); - // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. - app.UseHsts(); - } - - app.UseHttpsRedirection(); - app.UseStaticFiles(); - - app.UseRouting(); - - app.UseEndpoints(endpoints => { - endpoints.MapBlazorHub(); - endpoints.MapFallbackToPage("/_Host"); - }); - } - } -} diff --git a/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs b/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs index fc75579..ad60d1c 100644 --- a/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs +++ b/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered; +using EntityFrameworkCore.Triggered; namespace BlazorTests.Triggers.Counts { diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveAsyncTrigger.cs index e3339e4..ddd5291 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered { public interface IAfterSaveAsyncTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedAsyncTrigger.cs index 7daf819..cd3c30d 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedAsyncTrigger.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered { public interface IAfterSaveFailedAsyncTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedTrigger.cs index 2ff7cc0..68c5b41 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedTrigger.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered { public interface IAfterSaveFailedTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveAsyncTrigger.cs index 231bd7d..8580510 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered { public interface IBeforeSaveAsyncTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerContext.cs b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerContext.cs index 4bf9418..8dc280f 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerContext.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerContext.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; - -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered { public interface ITriggerContext where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerSession.cs b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerSession.cs index 3f01a50..46e5d93 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerSession.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerSession.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered { public interface ITriggerSession : IDisposable { diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedAsyncTrigger.cs index 20ef591..1efcef7 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles { public interface IAfterSaveCompletedAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedAsyncTrigger.cs index 3cef0fa..8e08b0e 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedAsyncTrigger.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles { public interface IAfterSaveFailedCompletedAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedTrigger.cs index 49a7eef..9fa24a5 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedTrigger.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles { public interface IAfterSaveFailedCompletedTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingAsyncTrigger.cs index 69ab9e0..91aa0b9 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingAsyncTrigger.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles { public interface IAfterSaveFailedStartingAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingTrigger.cs index 61de7aa..a25a1d5 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingTrigger.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles { public interface IAfterSaveFailedStartingTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingAsyncTrigger.cs index 75cba66..7c743ea 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles { public interface IAfterSaveStartingAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedAsyncTrigger.cs index 05302bd..d13a84d 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles { public interface IBeforeSaveCompletedAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingAsyncTrigger.cs index 950e116..2fee7cb 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles { public interface IBeforeSaveStartingAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs b/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs index 43d1d38..9e1a833 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using System.Reflection; +using System.Reflection; using EntityFrameworkCore.Triggered; using EntityFrameworkCore.Triggered.Infrastructure.Internal; using EntityFrameworkCore.Triggered.Lifecycles; diff --git a/src/EntityFrameworkCore.Triggered.Extensions/Trigger.cs b/src/EntityFrameworkCore.Triggered.Extensions/Trigger.cs index 3535a2c..9d01459 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/Trigger.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/Trigger.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Extensions +namespace EntityFrameworkCore.Triggered.Extensions { public class Trigger : IBeforeSaveTrigger, diff --git a/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs b/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs index 89394ed..120c49e 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; namespace EntityFrameworkCore.Triggered diff --git a/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs b/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs index cd77cdd..797eefc 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using System.Reflection; +using System.Reflection; using EntityFrameworkCore.Triggered.Infrastructure; using Microsoft.Extensions.DependencyInjection; diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitAsyncTrigger.cs index 9eaf195..75ab51b 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions { public interface IAfterCommitAsyncTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackAsyncTrigger.cs index 555fd8a..5f2270d 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions { public interface IAfterRollbackAsyncTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitAsyncTrigger.cs index f44ce14..dfabed8 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions { public interface IBeforeCommitAsyncTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackAsyncTrigger.cs index c42ae68..f9d640c 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions { public interface IBeforeRollbackAsyncTrigger where TEntity : class diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedAsyncTrigger.cs index 86debb9..eb16816 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles { public interface IAfterCommitCompletedAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingAsyncTrigger.cs index 0da265e..1402269 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles { public interface IAfterCommitStartingAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedAsyncTrigger.cs index e9be18b..b43fb8f 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles { public interface IBeforeCommitCompletedAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingAsyncTrigger.cs index 63faa27..59ea5d9 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingAsyncTrigger.cs @@ -1,7 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles { public interface IBeforeCommitStartingAsyncTrigger { diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs b/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs index 7124e3f..c1c387c 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Infrastructure; +using EntityFrameworkCore.Triggered.Infrastructure; using EntityFrameworkCore.Triggered.Transactions; using EntityFrameworkCore.Triggered.Transactions.Lifecycles; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitAsyncTriggerDescriptor.cs index 78ad20d..37b3fae 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitAsyncTriggerDescriptor.cs @@ -1,7 +1,4 @@ -using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; +using System.Diagnostics; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs index f317b42..e073158 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs @@ -1,5 +1,4 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackAsyncTriggerDescriptor.cs index bb507d0..5c1d7e1 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackAsyncTriggerDescriptor.cs @@ -1,7 +1,4 @@ -using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; +using System.Diagnostics; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs index b088ffc..5fa5730 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs @@ -1,5 +1,4 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitAsyncTriggerDescriptor.cs index 169c9c8..caf65e9 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitAsyncTriggerDescriptor.cs @@ -1,7 +1,4 @@ -using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; +using System.Diagnostics; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs index 602eb40..07cb5d3 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs @@ -1,5 +1,4 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackAsyncTriggerDescriptor.cs index 8c25e90..a33f88a 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackAsyncTriggerDescriptor.cs @@ -1,7 +1,4 @@ -using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; +using System.Diagnostics; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs index aacd54a..eee0dab 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs @@ -1,5 +1,4 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; diff --git a/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs b/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs index 28006ee..def5702 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Transactions; using EntityFrameworkCore.Triggered.Transactions.Internal; using EntityFrameworkCore.Triggered.Transactions.Lifecycles; diff --git a/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs b/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs index 131a330..6345bb3 100644 --- a/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs +++ b/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; namespace EntityFrameworkCore.Triggered.Extensions diff --git a/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs b/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs index 48ed647..9e4faaa 100644 --- a/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs +++ b/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection.Extensions; diff --git a/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs b/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs index 7c6eacc..4c58fc0 100644 --- a/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs +++ b/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Infrastructure; +using EntityFrameworkCore.Triggered.Infrastructure; using EntityFrameworkCore.Triggered.Infrastructure.Internal; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/src/EntityFrameworkCore.Triggered/ITriggerService.cs b/src/EntityFrameworkCore.Triggered/ITriggerService.cs index 9e00ca2..1f5d1d6 100644 --- a/src/EntityFrameworkCore.Triggered/ITriggerService.cs +++ b/src/EntityFrameworkCore.Triggered/ITriggerService.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; namespace EntityFrameworkCore.Triggered { diff --git a/src/EntityFrameworkCore.Triggered/ITriggerServiceProviderAccessor.cs b/src/EntityFrameworkCore.Triggered/ITriggerServiceProviderAccessor.cs index 28270a2..cb27c05 100644 --- a/src/EntityFrameworkCore.Triggered/ITriggerServiceProviderAccessor.cs +++ b/src/EntityFrameworkCore.Triggered/ITriggerServiceProviderAccessor.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered { public interface ITriggerServiceProviderAccessor { diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs index 1dc1bff..f94588e 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; +using System.Linq.Expressions; using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.CascadeStrategies; using EntityFrameworkCore.Triggered.Lifecycles; diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs index 9c2b745..306ceb7 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace EntityFrameworkCore.Triggered.Infrastructure.Internal +namespace EntityFrameworkCore.Triggered.Infrastructure.Internal { public static class TypeHelpers { diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs index b2febe7..c77959d 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Infrastructure.Internal; +using EntityFrameworkCore.Triggered.Infrastructure.Internal; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; diff --git a/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs b/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs index 3590528..be5f818 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; namespace EntityFrameworkCore.Triggered.Internal diff --git a/src/EntityFrameworkCore.Triggered/Internal/AsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/AsyncTriggerDescriptor.cs index c9efe17..0891356 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/AsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/AsyncTriggerDescriptor.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs index 2f8e84d..414c454 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveAsyncTriggerDescriptor.cs index ed1a0f1..ede6505 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveAsyncTriggerDescriptor.cs @@ -1,7 +1,4 @@ -using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; +using System.Diagnostics; namespace EntityFrameworkCore.Triggered.Internal.Descriptors { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptor.cs index f172331..4d1933e 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptor.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors { public sealed class AfterSaveFailedAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs index 571dcd8..4ae4043 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors { public sealed class AfterSaveFailedTriggerDescriptor : ITriggerTypeDescriptor { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs index 1c02947..b305198 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs @@ -1,5 +1,4 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; namespace EntityFrameworkCore.Triggered.Internal.Descriptors { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptor.cs index 807350b..a9e828e 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptor.cs @@ -1,7 +1,4 @@ -using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; +using System.Diagnostics; namespace EntityFrameworkCore.Triggered.Internal.Descriptors { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs index 5c517cc..7741510 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs @@ -1,5 +1,4 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; namespace EntityFrameworkCore.Triggered.Internal.Descriptors { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/IAsyncTriggerTypeDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/IAsyncTriggerTypeDescriptor.cs index 14ea4bb..df5f262 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/IAsyncTriggerTypeDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/IAsyncTriggerTypeDescriptor.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors { public interface IAsyncTriggerTypeDescriptor { diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/ITriggerTypeDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/ITriggerTypeDescriptor.cs index 71c00f7..8561ca8 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/ITriggerTypeDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/ITriggerTypeDescriptor.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors { public interface ITriggerTypeDescriptor diff --git a/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs b/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs index 1bc8268..e1f35a3 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; - -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal { public sealed class EntityBagStateManager { diff --git a/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs b/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs index b91e700..a85fdb0 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/ITriggerContextDiscoveryStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/ITriggerContextDiscoveryStrategy.cs index 6028e12..b621680 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ITriggerContextDiscoveryStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ITriggerContextDiscoveryStrategy.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/ITriggerDiscoveryService.cs b/src/EntityFrameworkCore.Triggered/Internal/ITriggerDiscoveryService.cs index e3ee4f8..58d52ce 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ITriggerDiscoveryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ITriggerDiscoveryService.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs b/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs index 86526bc..c229a11 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal { public interface ITriggerTypeRegistryService { diff --git a/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs index 938947b..b23b270 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs index aed2a37..ff9adab 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Concurrent; +using System.Collections.Concurrent; using Microsoft.EntityFrameworkCore.ChangeTracking; namespace EntityFrameworkCore.Triggered.Internal diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs index 8f3e9e3..1172e15 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs @@ -1,5 +1,4 @@ -using System; -using System.Linq.Expressions; +using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.ChangeTracking; namespace EntityFrameworkCore.Triggered.Internal diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs index 547782b..d5f59d7 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; -using System.Linq; -using EntityFrameworkCore.Triggered.Internal.CascadeStrategies; +using EntityFrameworkCore.Triggered.Internal.CascadeStrategies; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptor.cs index 74bd3c9..93b3963 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptor.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs index 1cec7a8..e6c4cc8 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; - -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal { public sealed class TriggerDescriptorComparer : IComparer, IComparer { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs index a4d5ca6..206e2d6 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; using Microsoft.EntityFrameworkCore.Infrastructure; namespace EntityFrameworkCore.Triggered.Internal diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs index 3c10da6..278c5e0 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; +using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; namespace EntityFrameworkCore.Triggered.Internal diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs index 4845c41..c3da71d 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; namespace EntityFrameworkCore.Triggered.Internal diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs index e8600bc..4a8afea 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs @@ -1,7 +1,4 @@ -using System; using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs index 42b0149..d99975e 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs @@ -1,7 +1,4 @@ -using System; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; +using System.Reflection; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs index adfd6cb..ee3d379 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using EntityFrameworkCore.Triggered.Infrastructure.Internal; +using EntityFrameworkCore.Triggered.Infrastructure.Internal; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs index 0032f82..75d417e 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Concurrent; +using System.Collections.Concurrent; namespace EntityFrameworkCore.Triggered.Internal { diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs index 1d26349..e1c77e5 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs @@ -1,5 +1,4 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/src/EntityFrameworkCore.Triggered/TriggerContext.cs b/src/EntityFrameworkCore.Triggered/TriggerContext.cs index 9d35244..db706c8 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerContext.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerContext.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using Microsoft.EntityFrameworkCore.ChangeTracking; namespace EntityFrameworkCore.Triggered diff --git a/src/EntityFrameworkCore.Triggered/TriggerService.cs b/src/EntityFrameworkCore.Triggered/TriggerService.cs index cba4ac5..20bdf03 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerService.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerService.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.CascadeStrategies; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/src/EntityFrameworkCore.Triggered/TriggerSession.cs b/src/EntityFrameworkCore.Triggered/TriggerSession.cs index bff8d08..402f95b 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerSession.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerSession.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; using EntityFrameworkCore.Triggered.Lifecycles; using Microsoft.Extensions.Logging; diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs index f84a310..a0e975a 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.Extensions.Tests +namespace EntityFrameworkCore.Triggered.Extensions.Tests { public abstract class AbstractTrigger : IBeforeSaveTrigger { diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTrigger.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTrigger.cs index 723cafa..d183c9b 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTrigger.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Lifecycles; +using EntityFrameworkCore.Triggered.Lifecycles; namespace EntityFrameworkCore.Triggered.Extensions.Tests { diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTriggerClone.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTriggerClone.cs index d25825c..796e7cc 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTriggerClone.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTriggerClone.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Lifecycles; +using EntityFrameworkCore.Triggered.Lifecycles; namespace EntityFrameworkCore.Triggered.Extensions.Tests { diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs index 9055c90..45c7feb 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs index fc01615..7f78a25 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs @@ -1,5 +1,4 @@ -using System.Linq; -using EntityFrameworkCore.Triggered.Infrastructure; +using EntityFrameworkCore.Triggered.Infrastructure; using EntityFrameworkCore.Triggered.Infrastructure.Internal; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Models/Branch.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Models/Branch.cs index 8e2a98c..1a59100 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Models/Branch.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Models/Branch.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; - -namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Models +namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Models { public class Branch { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs index 2239c50..49f0e41 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Extensions; +using EntityFrameworkCore.Triggered.Extensions; using EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Models; namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Triggers diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs index 684d474..c19f028 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers +namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers { public class SoftDeleteTrigger(ApplicationDbContext dbContext) : IBeforeSaveTrigger { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs index 8cf6739..48f6d19 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers +namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers { public class StampModifiedOnTrigger : IBeforeSaveTrigger { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/User.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/User.cs index e6a8922..92e6509 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/User.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/User.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags +namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags { public class User { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Models/User.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Models/User.cs index 1e1b0bf..9884363 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Models/User.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Models/User.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Models +namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Models { public class User { diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/TestScenario.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/TestScenario.cs index c0175eb..2bd7790 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/TestScenario.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/TestScenario.cs @@ -1,5 +1,4 @@ -using System.Linq; -using EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Models; +using EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Models; using ScenarioTests; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs index 00e552c..4d990b3 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Extensions; +using EntityFrameworkCore.Triggered.Extensions; using EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Models; namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Triggers.Users diff --git a/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs b/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs index b81c04b..78c49e0 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Extensions; +using EntityFrameworkCore.Triggered.Extensions; using EntityFrameworkCore.Triggered.Tests.Stubs; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs index 4da8318..68e3b2c 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Extensions; +using EntityFrameworkCore.Triggered.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs index f3cde62..ae80064 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Tests.Stubs; +using EntityFrameworkCore.Triggered.Tests.Stubs; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/TriggersContextOptionsBuilderTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/TriggersContextOptionsBuilderTests.cs index 91639d4..3deff3d 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/TriggersContextOptionsBuilderTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/TriggersContextOptionsBuilderTests.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Infrastructure; +using EntityFrameworkCore.Triggered.Infrastructure; using EntityFrameworkCore.Triggered.Infrastructure.Internal; using Microsoft.EntityFrameworkCore; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingTriggerContextDiscoveryStrategyTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingTriggerContextDiscoveryStrategyTests.cs index 6cbba26..53b8b74 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingTriggerContextDiscoveryStrategyTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingTriggerContextDiscoveryStrategyTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.CascadeStrategies; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveAsyncTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveAsyncTriggerDescriptorTests.cs index 5ee02e6..2569b14 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveAsyncTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveAsyncTriggerDescriptorTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptorTests.cs index 5b6e66f..40981a8 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptorTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs index 51d4ca5..29128ce 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptorTests.cs index 2f8ce6d..4e3e9d3 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptorTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal.Descriptors; +using EntityFrameworkCore.Triggered.Internal.Descriptors; using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/NonCascadingTriggerContextDiscoveryStrategyTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/NonCascadingTriggerContextDiscoveryStrategyTests.cs index af8a7d7..538a1eb 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/NonCascadingTriggerContextDiscoveryStrategyTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/NonCascadingTriggerContextDiscoveryStrategyTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.CascadeStrategies; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextFactoryTests.cs index 8f46b5f..ed57214 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextFactoryTests.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextTrackerTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextTrackerTests.cs index eeec426..409ad1d 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextTrackerTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextTrackerTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.CascadeStrategies; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs index 2d1e770..6e40efb 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs index 5410f7a..dbe2306 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; using EntityFrameworkCore.Triggered.Tests.Stubs; using Microsoft.Extensions.DependencyInjection; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs index 1862681..4c7bba2 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs index 2522978..f0f2d40 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Tests.Stubs; +using EntityFrameworkCore.Triggered.Tests.Stubs; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeDescriptorHelpersTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeDescriptorHelpersTests.cs index d16bde3..49df3ea 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeDescriptorHelpersTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeDescriptorHelpersTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryTests.cs index bb81130..eaf06a9 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryTests.cs @@ -1,5 +1,4 @@ -using System.Linq; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TypeHelpersTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TypeHelpersTests.cs index 5d57c48..767ab1a 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TypeHelpersTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TypeHelpersTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using EntityFrameworkCore.Triggered.Infrastructure.Internal; +using EntityFrameworkCore.Triggered.Infrastructure.Internal; using Xunit; namespace EntityFrameworkCore.Triggered.Tests.Internal diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs index 1bf1773..af136c1 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs { public class BeforeSaveDelegatingTrigger(Func, CancellationToken, Task> handler) : IBeforeSaveTrigger, IBeforeSaveAsyncTrigger where TEntity : class diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/OptionsSnapshotStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/OptionsSnapshotStub.cs index c5a81ee..2461d04 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/OptionsSnapshotStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/OptionsSnapshotStub.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.Extensions.Options; +using Microsoft.Extensions.Options; namespace EntityFrameworkCore.Triggered.Tests.Stubs { diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerContextStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerContextStub.cs index 970ba7a..a4c0f2a 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerContextStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerContextStub.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; - -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs { public class TriggerContextStub : ITriggerContext where TEntity : class diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs index 5c20568..66f1f17 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using EntityFrameworkCore.Triggered.Internal; +using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; using Microsoft.Extensions.DependencyInjection; diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs index bec9237..0d43ea3 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs @@ -1,6 +1,4 @@ -using System; - -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs { public class TriggerServiceProviderAccessorStub(IServiceProvider serviceProvider) : ITriggerServiceProviderAccessor { diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceStub.cs index 9f3d2c8..968e28e 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceStub.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; namespace EntityFrameworkCore.Triggered.Tests.Stubs { diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs index 446f392..e49ffae 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs { public class TriggerSessionStub : ITriggerSession { diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs index 1c5cabc..a2d1f69 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs { public class TriggerStub : IBeforeSaveTrigger, diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs index 7952333..b9c8067 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Tests.Stubs; +using EntityFrameworkCore.Triggered.Tests.Stubs; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs index fe739d9..1b17f96 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Tests.Stubs; +using EntityFrameworkCore.Triggered.Tests.Stubs; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs index cbb2e34..bb360f5 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; using Xunit; diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerContextStub.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerContextStub.cs index 3a3ed81..567881f 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerContextStub.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerContextStub.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; - -namespace EntityFrameworkCore.Triggered.Transactions.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Transactions.Tests.Stubs { public class TriggerContextStub : ITriggerContext where TEntity : class diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs index 7848b4d..425c509 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs @@ -1,7 +1,4 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Transactions.Lifecycles; +using EntityFrameworkCore.Triggered.Transactions.Lifecycles; namespace EntityFrameworkCore.Triggered.Transactions.Tests.Stubs { diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs index df03bea..76461f9 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs @@ -1,5 +1,4 @@ -using System; -using EntityFrameworkCore.Triggered.Extensions; +using EntityFrameworkCore.Triggered.Extensions; using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs index f4db1b6..62dd74f 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; +using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; From ecd190b767ff69974ea04ef7fbfca785f7d45fda Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 18:32:34 +0000 Subject: [PATCH 09/16] Convert to file scoped namespace --- .editorconfig | 2 +- .../ApplicationContext.cs | 83 +- .../EmbracingFeaturesBenchmarks.cs | 197 +++-- .../PlainOverheadBenchmarks.cs | 135 ++- .../Program.cs | 9 +- .../SetStudentRegistrationDateTrigger.cs | 9 +- .../SignStudentUpForMandatoryCourses.cs | 25 +- .../1 - HelloWorld/ApplicationDbContext.cs | 37 +- .../Triggers/StudentAssignRegistrationDate.cs | 13 +- .../2 - PrimarySchool/ApplicationDbContext.cs | 61 +- .../StudentSignupToMandatoryCourses.cs | 27 +- .../ApplicationDbContext.cs | 39 +- .../3 - StudentManagerAspNetCore/Models.cs | 59 +- .../Pages/Audits/Index.cshtml.cs | 13 +- .../Pages/Courses/Create.cshtml.cs | 35 +- .../Pages/Courses/Delete.cshtml.cs | 61 +- .../Pages/Courses/Details.cshtml.cs | 31 +- .../Pages/Courses/Edit.cshtml.cs | 77 +- .../Pages/Courses/Index.cshtml.cs | 13 +- .../Pages/Error.cshtml.cs | 17 +- .../Pages/Index.cshtml.cs | 13 +- .../Pages/Students/Create.cshtml.cs | 35 +- .../Pages/Students/Delete.cshtml.cs | 61 +- .../Pages/Students/Details.cshtml.cs | 31 +- .../Pages/Students/Edit.cshtml.cs | 77 +- .../Pages/Students/Index.cshtml.cs | 13 +- .../Services/EmailService.cs | 11 +- .../Traits/IAudited.cs | 9 +- .../Traits/ISoftDelete.cs | 9 +- .../Triggers/Courses/AutoSignupStudents.cs | 29 +- .../BlockRemovalWhenCourseIsMandatory.cs | 21 +- .../StudentCourses/SendWelcomingEmail.cs | 21 +- .../Students/AssignRegistrationDate.cs | 9 +- .../Students/SignupToMandatoryCourses.cs | 27 +- .../Traits/Audited/CreateAuditRecord.cs | 43 +- .../Traits/SoftDelete/EnsureSoftDelete.cs | 19 +- .../4 - BlazorTests/ApplicationDbContext.cs | 19 +- .../4 - BlazorTests/Data/WeatherForecast.cs | 15 +- .../Data/WeatherForecastService.cs | 31 +- samples/4 - BlazorTests/EventAggregator.cs | 17 +- samples/4 - BlazorTests/Pages/Error.cshtml.cs | 19 +- .../Triggers/Counts/PublishCountAddedEvent.cs | 17 +- .../Triggers/Counts/SetCreatedOn.cs | 9 +- .../ChangeType.cs | 13 +- .../CommonTriggerPriorities.cs | 19 +- .../IAfterSaveAsyncTrigger.cs | 11 +- .../IAfterSaveFailedAsyncTrigger.cs | 13 +- .../IAfterSaveFailedTrigger.cs | 13 +- .../IAfterSaveTrigger.cs | 11 +- .../IBeforeSaveAsyncTrigger.cs | 11 +- .../IBeforeSaveTrigger.cs | 11 +- .../ITriggerContext.cs | 41 +- .../ITriggerPriority.cs | 15 +- .../ITriggerSession.cs | 115 ++- .../IAfterSaveCompletedAsyncTrigger.cs | 9 +- .../Lifecycles/IAfterSaveCompletedTrigger.cs | 9 +- .../IAfterSaveFailedCompletedAsyncTrigger.cs | 9 +- .../IAfterSaveFailedCompletedTrigger.cs | 9 +- .../IAfterSaveFailedStartingAsyncTrigger.cs | 9 +- .../IAfterSaveFailedStartingTrigger.cs | 9 +- .../IAfterSaveStartingAsyncTrigger.cs | 9 +- .../Lifecycles/IAfterSaveStartingTrigger.cs | 9 +- .../IBeforeSaveCompletedAsyncTrigger.cs | 9 +- .../Lifecycles/IBeforeSaveCompletedTrigger.cs | 9 +- .../IBeforeSaveStartingAsyncTrigger.cs | 9 +- .../Lifecycles/IBeforeSaveStartingTrigger.cs | 9 +- .../TriggerSessionConfiguration.cs | 19 +- .../ServiceCollectionExtensions.cs | 149 ++-- .../Trigger.cs | 35 +- .../TriggerContextExtensions.cs | 51 +- ...TriggersContextOptionsBuilderExtensions.cs | 43 +- .../IAfterCommitAsyncTrigger.cs | 11 +- .../IAfterCommitTrigger.cs | 11 +- .../IAfterRollbackAsyncTrigger.cs | 11 +- .../IAfterRollbackTrigger.cs | 11 +- .../IBeforeCommitAsyncTrigger.cs | 11 +- .../IBeforeCommitTrigger.cs | 11 +- .../IBeforeRollbackAsyncTrigger.cs | 11 +- .../IBeforeRollbackTrigger.cs | 11 +- .../IAfterCommitCompletedAsyncTrigger.cs | 9 +- .../IAfterCommitCompletedTrigger.cs | 9 +- .../IAfterCommitStartingAsyncTrigger.cs | 9 +- .../Lifecycles/IAfterCommitStartingTrigger.cs | 9 +- .../IBeforeCommitCompletedAsyncTrigger.cs | 9 +- .../IBeforeCommitCompletedTrigger.cs | 9 +- .../IBeforeCommitStartingAsyncTrigger.cs | 9 +- .../IBeforeCommitStartingTrigger.cs | 9 +- ...TriggersContextOptionsBuilderExtensions.cs | 45 +- .../AfterCommitAsyncTriggerDescriptor.cs | 35 +- .../Internal/AfterCommitTriggerDescriptor.cs | 35 +- .../AfterRollbackAsyncTriggerDescriptor.cs | 35 +- .../AfterRollbackTriggerDescriptor.cs | 35 +- .../BeforeCommitAsyncTriggerDescriptor.cs | 35 +- .../Internal/BeforeCommitTriggerDescriptor.cs | 35 +- .../BeforeRollbackAsyncTriggerDescriptor.cs | 35 +- .../BeforeRollbackTriggerDescriptor.cs | 35 +- .../TriggeredSessionExtensions.cs | 299 ++++--- .../Extensions/DbContextExtensions.cs | 127 ++- .../Extensions/ServiceCollectionExtensions.cs | 277 +++--- .../TriggersDbContextOptionsExtensions.cs | 31 +- .../ITriggerService.cs | 15 +- .../ITriggerServiceProviderAccessor.cs | 9 +- .../Infrastructure/CascadeBehavior.cs | 29 +- .../Internal/TriggersOptionExtension.cs | 455 +++++----- .../Infrastructure/Internal/TypeHelpers.cs | 25 +- .../TriggersContextOptionsBuilder.cs | 63 +- ...plicationTriggerServiceProviderAccessor.cs | 111 ++- .../Internal/AsyncTriggerDescriptor.cs | 45 +- .../EntityAndTypeCascadeStrategy.cs | 11 +- .../CascadeStrategies/ICascadeStrategy.cs | 9 +- .../CascadeStrategies/NoCascadeStrategy.cs | 11 +- ...ascadingTriggerContextDiscoveryStrategy.cs | 83 +- .../AfterSaveAsyncTriggerDescriptor.cs | 35 +- .../AfterSaveFailedAsyncTriggerDescriptor.cs | 31 +- .../AfterSaveFailedTriggerDescriptor.cs | 31 +- .../Descriptors/AfterSaveTriggerDescriptor.cs | 35 +- .../BeforeSaveAsyncTriggerDescriptor.cs | 35 +- .../BeforeSaveTriggerDescriptor.cs | 35 +- .../IAsyncTriggerTypeDescriptor.cs | 12 +- .../Descriptors/ITriggerTypeDescriptor.cs | 12 +- .../Internal/EntityStateBagManager.cs | 23 +- .../Internal/HybridServiceProvider.cs | 35 +- .../ITriggerContextDiscoveryStrategy.cs | 9 +- .../Internal/ITriggerDiscoveryService.cs | 15 +- .../Internal/ITriggerTypeRegistryService.cs | 9 +- ...ascadingTriggerContextDiscoveryStrategy.cs | 33 +- .../Internal/TriggerContextDescriptor.cs | 51 +- .../Internal/TriggerContextFactory.cs | 49 +- .../Internal/TriggerContextTracker.cs | 173 ++-- .../Internal/TriggerDescriptor.cs | 45 +- .../Internal/TriggerDescriptorComparer.cs | 27 +- .../Internal/TriggerDiscoveryService.cs | 183 ++-- .../Internal/TriggerFactory.cs | 49 +- .../Internal/TriggerInstanceFactory.cs | 55 +- .../TriggerSessionSaveChangesInterceptor.cs | 272 +++--- .../Internal/TriggerTypeDescriptorHelpers.cs | 117 ++- .../Internal/TriggerTypeRegistry.cs | 55 +- .../Internal/TriggerTypeRegistryService.cs | 31 +- .../Internal/TriggeredDbContextFactory.cs | 61 +- .../TriggerContext.cs | 51 +- .../TriggerOptions.cs | 9 +- .../TriggerService.cs | 97 ++- .../TriggerSession.cs | 461 +++++----- .../AbstractTrigger.cs | 9 +- .../SampleTrigger.cs | 35 +- .../SampleTriggerClone.cs | 35 +- .../ServiceCollectionExtensionsTests.cs | 465 +++++----- .../TriggerContextExtensionsTests.cs | 63 +- ...gerContextOptionsBuilderExtensionsTests.cs | 23 +- .../ApplicationDbContext.cs | 33 +- .../CascadingSoftDeletesTestScenario.cs | 83 +- .../CascadingSoftDeletes/Models/Branch.cs | 17 +- .../Triggers/SoftDelete.cs | 19 +- .../EntityBags/ApplicationDbContext.cs | 9 +- .../EntityBags/EntityBagsTestScenario.cs | 65 +- .../EntityBags/Triggers/SoftDeleteTrigger.cs | 23 +- .../Triggers/StampModifiedOnTrigger.cs | 15 +- .../EntityBags/User.cs | 15 +- .../LifetimeTests/ApplicationDbContext.cs | 9 +- .../TriggerLifetimeTestScenario.cs | 85 +- .../Triggers/Users/ScopedTrigger.cs | 15 +- .../Triggers/Users/SingletonTrigger.cs | 17 +- .../Triggers/Users/TransientTrigger.cs | 15 +- .../LifetimeTests/User.cs | 9 +- .../SampleStore/ApplicationDbContext.cs | 25 +- .../SampleStore/Models/User.cs | 13 +- .../SampleStore/TestScenario.cs | 81 +- .../Triggers/Users/SoftDeleteUsers.cs | 19 +- .../EFCore5DbContextTests.cs | 259 +++--- .../Extensions/DbContextExtensionTests.cs | 211 +++-- .../ServiceCollectionExtensionsTests.cs | 349 ++++---- .../TriggersContextOptionsBuilderTests.cs | 59 +- ...tionTriggerServiceProviderAccessorTests.cs | 115 ++- .../EntityAndTypeRecursionStrategyTests.cs | 19 +- .../NoRecursionStrategyTests.cs | 19 +- .../RecursionStrategyTestsBase.cs | 123 ++- ...ingTriggerContextDiscoveryStrategyTests.cs | 73 +- .../AfterSaveAsyncTriggerDescriptorTests.cs | 35 +- ...erSaveFailedAsyncTriggerDescriptorTests.cs | 39 +- .../AfterSaveFailedTriggerDescriptorTests.cs | 39 +- .../AfterSaveTriggerDescriptorTests.cs | 35 +- .../BeforeSaveAsyncTriggerDescriptorTests.cs | 35 +- .../BeforeSaveTriggerDescriptorTests.cs | 35 +- .../Internal/EntityBagStateManagerTests.cs | 41 +- .../Internal/HybridServiceProviderTests.cs | 89 +- ...ingTriggerContextDiscoveryStrategyTests.cs | 63 +- .../RecursionStrategyTestsBase.cs | 127 ++- .../Internal/TriggerContextFactoryTests.cs | 51 +- .../Internal/TriggerContextTrackerTests.cs | 247 +++--- .../Internal/TriggerDescriptorTests.cs | 45 +- .../Internal/TriggerDiscoveryServiceTests.cs | 229 +++-- .../Internal/TriggerFactoryTests.cs | 175 ++-- .../Internal/TriggerInstanceFactoryTests.cs | 85 +- ...iggerSessionSaveChangesInterceptorTests.cs | 491 ++++++----- .../TriggerTypeDescriptorHelpersTests.cs | 39 +- .../TriggerTypeRegistryServiceTests.cs | 75 +- .../Internal/TriggerTypeRegistryTests.cs | 111 ++- .../Internal/TypeHelpersTests.cs | 37 +- .../Stubs/BeforeSaveDelegatingTrigger.cs | 15 +- .../Stubs/EventDefinitionBaseStub.cs | 11 +- .../Stubs/OptionsSnapshotStub.cs | 13 +- .../Stubs/TriggerContextStub.cs | 19 +- .../Stubs/TriggerDiscoveryServiceStub.cs | 21 +- .../TriggerServiceProviderAccessorStub.cs | 11 +- .../Stubs/TriggerServiceStub.cs | 35 +- .../Stubs/TriggerSessionStub.cs | 217 +++-- .../Stubs/TriggerStub.cs | 119 ++- .../TriggerContextTests.cs | 175 ++-- ...ggerServiceApplicationDependenciesTests.cs | 261 +++--- .../TriggerServiceTests.cs | 85 +- .../TriggerSessionTests.cs | 791 +++++++++--------- .../TriggeredDbContextFactoryTests.cs | 91 +- .../AfterCommitTriggerDescriptorTests.cs | 35 +- .../AfterRollbackTriggerDescriptorTests.cs | 35 +- .../BeforeCommitTriggerDescriptorTests.cs | 35 +- .../BeforeRollbackTriggerDescriptorTests.cs | 35 +- .../Stubs/TriggerContextStub.cs | 17 +- .../Stubs/TriggerStub.cs | 201 +++-- .../TriggeredDbContextTests.cs | 99 ++- .../TriggeredSessionExtensionsTests.cs | 535 ++++++------ 220 files changed, 6787 insertions(+), 7013 deletions(-) diff --git a/.editorconfig b/.editorconfig index 5f2d62c..98126ff 100644 --- a/.editorconfig +++ b/.editorconfig @@ -134,7 +134,7 @@ dotnet_naming_style.instance_field_style.required_prefix = _ csharp_indent_labels = one_less_than_current csharp_using_directive_placement = outside_namespace:silent csharp_prefer_simple_using_statement = true:suggestion -csharp_style_namespace_declarations = block_scoped:silent +csharp_style_namespace_declarations = file_scoped:silent csharp_style_prefer_method_group_conversion = true:silent csharp_style_prefer_top_level_statements = true:silent csharp_style_prefer_primary_constructors = true:suggestion diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs index 55449c8..6232365 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/ApplicationContext.cs @@ -1,70 +1,69 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -namespace EntityFrameworkCore.Triggered.Benchmarks +namespace EntityFrameworkCore.Triggered.Benchmarks; + +public class Student { - public class Student - { - public Guid Id { get; set; } + public Guid Id { get; set; } - public string DisplayName { get; set; } + public string DisplayName { get; set; } - public DateTimeOffset RegistrationDate { get; set; } - } + public DateTimeOffset RegistrationDate { get; set; } +} - public class Course - { - public Guid Id { get; set; } +public class Course +{ + public Guid Id { get; set; } - public string DisplayName { get; set; } + public string DisplayName { get; set; } - public bool IsMandatory { get; set; } + public bool IsMandatory { get; set; } - } +} - public class StudentCourse - { - public Guid StudentId { get; set; } +public class StudentCourse +{ + public Guid StudentId { get; set; } - public Guid CourseId { get; set; } + public Guid CourseId { get; set; } - public Student Student { get; set; } + public Student Student { get; set; } - public Course Course { get; set; } - } + public Course Course { get; set; } +} - public interface IApplicationContextContract : IDisposable - { - DatabaseFacade Database { get; } +public interface IApplicationContextContract : IDisposable +{ + DatabaseFacade Database { get; } - int SaveChanges(); + int SaveChanges(); - DbSet Students { get; set; } + DbSet Students { get; set; } - DbSet Courses { get; set; } + DbSet Courses { get; set; } - DbSet StudentCourses { get; set; } - } + DbSet StudentCourses { get; set; } +} - public class ApplicationContext(DbContextOptions options) : DbContext(options), IApplicationContextContract - { - protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasKey(x => new { x.StudentId, x.CourseId }); +public class ApplicationContext(DbContextOptions options) : DbContext(options), IApplicationContextContract +{ + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasKey(x => new { x.StudentId, x.CourseId }); - public DbSet Students { get; set; } + public DbSet Students { get; set; } - public DbSet Courses { get; set; } + public DbSet Courses { get; set; } - public DbSet StudentCourses { get; set; } - } + public DbSet StudentCourses { get; set; } +} - public class TriggeredApplicationContext(DbContextOptions options) : DbContext(options), IApplicationContextContract - { - protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasKey(x => new { x.StudentId, x.CourseId }); +public class TriggeredApplicationContext(DbContextOptions options) : DbContext(options), IApplicationContextContract +{ + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasKey(x => new { x.StudentId, x.CourseId }); - public DbSet Students { get; set; } + public DbSet Students { get; set; } - public DbSet Courses { get; set; } + public DbSet Courses { get; set; } - public DbSet StudentCourses { get; set; } - } + public DbSet StudentCourses { get; set; } } diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs index ff08434..6e97b94 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EmbracingFeaturesBenchmarks.cs @@ -2,133 +2,132 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -namespace EntityFrameworkCore.Triggered.Benchmarks +namespace EntityFrameworkCore.Triggered.Benchmarks; + +[MemoryDiagnoser] +public class EmbracingFeaturesBenchmarks { - [MemoryDiagnoser] - public class EmbracingFeaturesBenchmarks + private IServiceProvider _serviceProvider; + + [GlobalSetup] + public void GlobalSetup() => _serviceProvider = new ServiceCollection() + .AddDbContext(options => { + options + .UseInMemoryDatabase(nameof(WithDbContext)); + }) + .AddTriggeredDbContext(options => { + options + .UseInMemoryDatabase(nameof(WithTriggeredDbContext)) + .UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(); + triggerOptions.AddTrigger(); + }); + }) + .BuildServiceProvider(); + + [Params(50)] + public int OuterBatches; + + [Params(1, 10, 100)] + public int InnerBatches; + + private void Validate(IApplicationContextContract applicationContextContract) { - private IServiceProvider _serviceProvider; - - [GlobalSetup] - public void GlobalSetup() => _serviceProvider = new ServiceCollection() - .AddDbContext(options => { - options - .UseInMemoryDatabase(nameof(WithDbContext)); - }) - .AddTriggeredDbContext(options => { - options - .UseInMemoryDatabase(nameof(WithTriggeredDbContext)) - .UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(); - triggerOptions.AddTrigger(); - }); - }) - .BuildServiceProvider(); - - [Params(50)] - public int OuterBatches; - - [Params(1, 10, 100)] - public int InnerBatches; - - private void Validate(IApplicationContextContract applicationContextContract) - { - var studentCoursesCount = applicationContextContract.StudentCourses.Count(); - var expectedCoursesCount = OuterBatches * InnerBatches; + var studentCoursesCount = applicationContextContract.StudentCourses.Count(); + var expectedCoursesCount = OuterBatches * InnerBatches; - if (studentCoursesCount != expectedCoursesCount) - { - throw new InvalidOperationException($"Found {studentCoursesCount}, expected {expectedCoursesCount}"); - } + if (studentCoursesCount != expectedCoursesCount) + { + throw new InvalidOperationException($"Found {studentCoursesCount}, expected {expectedCoursesCount}"); } + } - [Benchmark(Baseline = true)] - public void WithDbContext() + [Benchmark(Baseline = true)] + public void WithDbContext() + { + // setup { - // setup - { - using var scope = _serviceProvider.CreateScope(); - using var context = scope.ServiceProvider.GetRequiredService(); + using var scope = _serviceProvider.CreateScope(); + using var context = scope.ServiceProvider.GetRequiredService(); - context.Database.EnsureDeleted(); + context.Database.EnsureDeleted(); - context.Courses.Add(new Course { Id = Guid.NewGuid(), DisplayName = "Test", IsMandatory = true }); - context.SaveChanges(); - } + context.Courses.Add(new Course { Id = Guid.NewGuid(), DisplayName = "Test", IsMandatory = true }); + context.SaveChanges(); + } - // execute - for (var outerBatch = 0; outerBatch < OuterBatches; outerBatch++) - { - using var scope = _serviceProvider.CreateScope(); - using var context = scope.ServiceProvider.GetRequiredService(); + // execute + for (var outerBatch = 0; outerBatch < OuterBatches; outerBatch++) + { + using var scope = _serviceProvider.CreateScope(); + using var context = scope.ServiceProvider.GetRequiredService(); - for (var innerBatch = 0; innerBatch < InnerBatches; innerBatch++) - { - var student = new Student { Id = Guid.NewGuid(), DisplayName = "Test" }; - student.RegistrationDate = DateTimeOffset.Now; + for (var innerBatch = 0; innerBatch < InnerBatches; innerBatch++) + { + var student = new Student { Id = Guid.NewGuid(), DisplayName = "Test" }; + student.RegistrationDate = DateTimeOffset.Now; - context.Add(student); + context.Add(student); - var mandatoryCourses = context.Courses.Where(x => x.IsMandatory).ToList(); + var mandatoryCourses = context.Courses.Where(x => x.IsMandatory).ToList(); - foreach (var mandatoryCourse in mandatoryCourses) - { - context.StudentCourses.Add(new StudentCourse { - CourseId = mandatoryCourse.Id, - StudentId = student.Id - }); - } + foreach (var mandatoryCourse in mandatoryCourses) + { + context.StudentCourses.Add(new StudentCourse { + CourseId = mandatoryCourse.Id, + StudentId = student.Id + }); } - - context.SaveChanges(); } - // validate - { - using var scope = _serviceProvider.CreateScope(); - using var context = scope.ServiceProvider.GetRequiredService(); - - Validate(context); - } + context.SaveChanges(); } - [Benchmark] - public void WithTriggeredDbContext() + // validate { - // setup - { - using var scope = _serviceProvider.CreateScope(); - using var context = scope.ServiceProvider.GetRequiredService(); + using var scope = _serviceProvider.CreateScope(); + using var context = scope.ServiceProvider.GetRequiredService(); - context.Database.EnsureDeleted(); + Validate(context); + } + } - context.Courses.Add(new Course { Id = Guid.NewGuid(), DisplayName = "Test", IsMandatory = true }); - context.SaveChanges(); - } + [Benchmark] + public void WithTriggeredDbContext() + { + // setup + { + using var scope = _serviceProvider.CreateScope(); + using var context = scope.ServiceProvider.GetRequiredService(); - // execute - for (var outerBatch = 0; outerBatch < OuterBatches; outerBatch++) - { - using var scope = _serviceProvider.CreateScope(); - using var context = scope.ServiceProvider.GetRequiredService(); + context.Database.EnsureDeleted(); - for (var innerBatch = 0; innerBatch < InnerBatches; innerBatch++) - { - var student = new Student { Id = Guid.NewGuid(), DisplayName = "Test" }; - context.Add(student); - } + context.Courses.Add(new Course { Id = Guid.NewGuid(), DisplayName = "Test", IsMandatory = true }); + context.SaveChanges(); + } + + // execute + for (var outerBatch = 0; outerBatch < OuterBatches; outerBatch++) + { + using var scope = _serviceProvider.CreateScope(); + using var context = scope.ServiceProvider.GetRequiredService(); - context.SaveChanges(); + for (var innerBatch = 0; innerBatch < InnerBatches; innerBatch++) + { + var student = new Student { Id = Guid.NewGuid(), DisplayName = "Test" }; + context.Add(student); } + context.SaveChanges(); + } - // validate - { - using var scope = _serviceProvider.CreateScope(); - using var context = scope.ServiceProvider.GetRequiredService(); - Validate(context); - } + // validate + { + using var scope = _serviceProvider.CreateScope(); + using var context = scope.ServiceProvider.GetRequiredService(); + + Validate(context); } } } diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs index 4ca303c..2f066d7 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/PlainOverheadBenchmarks.cs @@ -2,91 +2,90 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -namespace EntityFrameworkCore.Triggered.Benchmarks +namespace EntityFrameworkCore.Triggered.Benchmarks; + +[MemoryDiagnoser] +public class PlainOverheadBenchmarks { - [MemoryDiagnoser] - public class PlainOverheadBenchmarks + IServiceProvider _serviceProvider; + + [GlobalSetup] + public void GlobalSetup() => _serviceProvider = new ServiceCollection() + .AddDbContext(options => { + options + .UseInMemoryDatabase(nameof(WithDbContext)); + }) + .AddDbContext(options => { + options + .UseInMemoryDatabase(nameof(WithTriggeredDbContext)) + .UseTriggers(); + }) + .BuildServiceProvider(); + + [Params(50)] + public int OuterBatches; + + [Params(1, 10, 100)] + public int InnerBatches; + + void Execute() + where TApplicationContext : IApplicationContextContract { - IServiceProvider _serviceProvider; - - [GlobalSetup] - public void GlobalSetup() => _serviceProvider = new ServiceCollection() - .AddDbContext(options => { - options - .UseInMemoryDatabase(nameof(WithDbContext)); - }) - .AddDbContext(options => { - options - .UseInMemoryDatabase(nameof(WithTriggeredDbContext)) - .UseTriggers(); - }) - .BuildServiceProvider(); - - [Params(50)] - public int OuterBatches; - - [Params(1, 10, 100)] - public int InnerBatches; - - void Execute() - where TApplicationContext : IApplicationContextContract + // setup { - // setup - { - using var scope = _serviceProvider.CreateScope(); - using var context = scope.ServiceProvider.GetRequiredService() as IApplicationContextContract; + using var scope = _serviceProvider.CreateScope(); + using var context = scope.ServiceProvider.GetRequiredService() as IApplicationContextContract; - context.Database.EnsureDeleted(); + context.Database.EnsureDeleted(); - context.Courses.Add(new Course { Id = Guid.NewGuid(), DisplayName = "Test", IsMandatory = true }); - context.SaveChanges(); - } + context.Courses.Add(new Course { Id = Guid.NewGuid(), DisplayName = "Test", IsMandatory = true }); + context.SaveChanges(); + } - // Here we do everything manually - for (var outerBatch = 0; outerBatch < OuterBatches; outerBatch++) - { - using var scope = _serviceProvider.CreateScope(); - using var context = scope.ServiceProvider.GetRequiredService(); + // Here we do everything manually + for (var outerBatch = 0; outerBatch < OuterBatches; outerBatch++) + { + using var scope = _serviceProvider.CreateScope(); + using var context = scope.ServiceProvider.GetRequiredService(); - for (var innerBatch = 0; innerBatch < InnerBatches; innerBatch++) - { - var student = new Student { Id = Guid.NewGuid(), DisplayName = "Test" }; - student.RegistrationDate = DateTimeOffset.Now; + for (var innerBatch = 0; innerBatch < InnerBatches; innerBatch++) + { + var student = new Student { Id = Guid.NewGuid(), DisplayName = "Test" }; + student.RegistrationDate = DateTimeOffset.Now; - context.Students.Add(student); + context.Students.Add(student); - var mandatoryCourses = context.Courses.Where(x => x.IsMandatory).ToList(); + var mandatoryCourses = context.Courses.Where(x => x.IsMandatory).ToList(); - foreach (var mandatoryCourse in mandatoryCourses) - { - context.StudentCourses.Add(new StudentCourse { - CourseId = mandatoryCourse.Id, - StudentId = student.Id - }); - } + foreach (var mandatoryCourse in mandatoryCourses) + { + context.StudentCourses.Add(new StudentCourse { + CourseId = mandatoryCourse.Id, + StudentId = student.Id + }); } - - context.SaveChanges(); } - // validation - { - using var scope = _serviceProvider.CreateScope(); - using var context = scope.ServiceProvider.GetRequiredService(); + context.SaveChanges(); + } - var studentCoursesCount = context.StudentCourses.Count(); + // validation + { + using var scope = _serviceProvider.CreateScope(); + using var context = scope.ServiceProvider.GetRequiredService(); - if (studentCoursesCount != OuterBatches * InnerBatches) - { - throw new InvalidOperationException(); - } + var studentCoursesCount = context.StudentCourses.Count(); + + if (studentCoursesCount != OuterBatches * InnerBatches) + { + throw new InvalidOperationException(); } } + } - [Benchmark(Baseline = true)] - public void WithDbContext() => Execute(); + [Benchmark(Baseline = true)] + public void WithDbContext() => Execute(); - [Benchmark] - public void WithTriggeredDbContext() => Execute(); - } + [Benchmark] + public void WithTriggeredDbContext() => Execute(); } diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Program.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Program.cs index 707fe9e..cf239d2 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Program.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Program.cs @@ -1,10 +1,9 @@ using BenchmarkDotNet.Configs; using BenchmarkDotNet.Running; -namespace EntityFrameworkCore.Triggered.Benchmarks +namespace EntityFrameworkCore.Triggered.Benchmarks; + +public class Program { - public class Program - { - public static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, DefaultConfig.Instance.WithOption(ConfigOptions.DisableOptimizationsValidator, true)); - } + public static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, DefaultConfig.Instance.WithOption(ConfigOptions.DisableOptimizationsValidator, true)); } \ No newline at end of file diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs index 90584e3..35f31b2 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SetStudentRegistrationDateTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers +namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers; + +public class SetStudentRegistrationDateTrigger : IBeforeSaveTrigger { - public class SetStudentRegistrationDateTrigger : IBeforeSaveTrigger - { - public void BeforeSave(ITriggerContext context) => context.Entity.RegistrationDate = DateTimeOffset.Now; - } + public void BeforeSave(ITriggerContext context) => context.Entity.RegistrationDate = DateTimeOffset.Now; } diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs index 6f8ec68..d1776ce 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/Triggers/SignStudentUpForMandatoryCourses.cs @@ -1,20 +1,19 @@ -namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers +namespace EntityFrameworkCore.Triggered.Benchmarks.Triggers; + +public class SignStudentUpForMandatoryCourses(TriggeredApplicationContext applicationContext) : IBeforeSaveTrigger { - public class SignStudentUpForMandatoryCourses(TriggeredApplicationContext applicationContext) : IBeforeSaveTrigger + readonly TriggeredApplicationContext _applicationContext = applicationContext; + + public void BeforeSave(ITriggerContext context) { - readonly TriggeredApplicationContext _applicationContext = applicationContext; + var mandatoryCourses = _applicationContext.Courses.Where(x => x.IsMandatory).ToList(); - public void BeforeSave(ITriggerContext context) + foreach (var mandatoryCourse in mandatoryCourses) { - var mandatoryCourses = _applicationContext.Courses.Where(x => x.IsMandatory).ToList(); - - foreach (var mandatoryCourse in mandatoryCourses) - { - _applicationContext.StudentCourses.Add(new StudentCourse { - CourseId = mandatoryCourse.Id, - StudentId = context.Entity.Id - }); - } + _applicationContext.StudentCourses.Add(new StudentCourse { + CourseId = mandatoryCourse.Id, + StudentId = context.Entity.Id + }); } } } diff --git a/samples/1 - HelloWorld/ApplicationDbContext.cs b/samples/1 - HelloWorld/ApplicationDbContext.cs index 635195b..dd95155 100644 --- a/samples/1 - HelloWorld/ApplicationDbContext.cs +++ b/samples/1 - HelloWorld/ApplicationDbContext.cs @@ -1,29 +1,28 @@ using Microsoft.EntityFrameworkCore; -namespace PrimarySchool +namespace PrimarySchool; + +public class Student { - public class Student - { - public int Id { get; set; } + public int Id { get; set; } - public string DisplayName { get; set; } + public string DisplayName { get; set; } - public DateTime RegistrationDate { get; set; } - } + public DateTime RegistrationDate { get; set; } +} - public class ApplicationDbContext : DbContext +public class ApplicationDbContext : DbContext +{ + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder - .UseInMemoryDatabase("HelloWorld") - .UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(); - }); - - base.OnConfiguring(optionsBuilder); - } + optionsBuilder + .UseInMemoryDatabase("HelloWorld") + .UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(); + }); - public DbSet Students { get; set; } + base.OnConfiguring(optionsBuilder); } + + public DbSet Students { get; set; } } diff --git a/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs b/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs index 64cd27c..fcee7cb 100644 --- a/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs +++ b/samples/1 - HelloWorld/Triggers/StudentAssignRegistrationDate.cs @@ -1,15 +1,14 @@ using EntityFrameworkCore.Triggered; -namespace PrimarySchool.Triggers +namespace PrimarySchool.Triggers; + +public class StudentAssignRegistrationDate : IBeforeSaveTrigger { - public class StudentAssignRegistrationDate : IBeforeSaveTrigger + public void BeforeSave(ITriggerContext context) { - public void BeforeSave(ITriggerContext context) + if (context.ChangeType == ChangeType.Added) { - if (context.ChangeType == ChangeType.Added) - { - context.Entity.RegistrationDate = DateTime.Today; - } + context.Entity.RegistrationDate = DateTime.Today; } } } diff --git a/samples/2 - PrimarySchool/ApplicationDbContext.cs b/samples/2 - PrimarySchool/ApplicationDbContext.cs index 3d344e3..8390d1c 100644 --- a/samples/2 - PrimarySchool/ApplicationDbContext.cs +++ b/samples/2 - PrimarySchool/ApplicationDbContext.cs @@ -1,52 +1,51 @@ using Microsoft.EntityFrameworkCore; -namespace PrimarySchool +namespace PrimarySchool; + +public class Student { - public class Student - { - public int Id { get; set; } + public int Id { get; set; } - public string DisplayName { get; set; } + public string DisplayName { get; set; } - public DateTimeOffset RegistrationDate { get; set; } - } + public DateTimeOffset RegistrationDate { get; set; } +} - public class Course - { - public int Id { get; set; } +public class Course +{ + public int Id { get; set; } - public string DisplayName { get; set; } + public string DisplayName { get; set; } - public bool IsMandatory { get; set; } + public bool IsMandatory { get; set; } - } +} - public class StudentCourse - { - public int StudentId { get; set; } +public class StudentCourse +{ + public int StudentId { get; set; } - public int CourseId { get; set; } + public int CourseId { get; set; } - public Student Student { get; set; } + public Student Student { get; set; } - public Course Course { get; set; } - } + public Course Course { get; set; } +} - public class ApplicationDbContext(DbContextOptions options) : DbContext(options) +public class ApplicationDbContext(DbContextOptions options) : DbContext(options) +{ + protected override void OnModelCreating(ModelBuilder modelBuilder) { - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity() - .HasKey(x => new { x.StudentId, x.CourseId }); + modelBuilder.Entity() + .HasKey(x => new { x.StudentId, x.CourseId }); - base.OnModelCreating(modelBuilder); - } + base.OnModelCreating(modelBuilder); + } - public DbSet Students { get; set; } + public DbSet Students { get; set; } - public DbSet Courses { get; set; } + public DbSet Courses { get; set; } - public DbSet StudentCourses { get; set; } - } + public DbSet StudentCourses { get; set; } } diff --git a/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs b/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs index 781e65b..2218cc2 100644 --- a/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs +++ b/samples/2 - PrimarySchool/Triggers/StudentSignupToMandatoryCourses.cs @@ -1,24 +1,23 @@ using EntityFrameworkCore.Triggered; -namespace PrimarySchool.Triggers +namespace PrimarySchool.Triggers; + +public class StudentSignupToMandatoryCourses(ApplicationDbContext applicationContext) : IBeforeSaveTrigger { - public class StudentSignupToMandatoryCourses(ApplicationDbContext applicationContext) : IBeforeSaveTrigger + readonly ApplicationDbContext _applicationContext = applicationContext; + + public void BeforeSave(ITriggerContext context) { - readonly ApplicationDbContext _applicationContext = applicationContext; + var mandatoryCourses = _applicationContext.Courses + .Where(x => x.IsMandatory) + .ToList(); - public void BeforeSave(ITriggerContext context) + foreach (var mandatoryCourse in mandatoryCourses) { - var mandatoryCourses = _applicationContext.Courses - .Where(x => x.IsMandatory) - .ToList(); - - foreach (var mandatoryCourse in mandatoryCourses) + var studentRegistration = _applicationContext.StudentCourses.Find(context.Entity.Id, mandatoryCourse.Id); + if (studentRegistration == null) { - var studentRegistration = _applicationContext.StudentCourses.Find(context.Entity.Id, mandatoryCourse.Id); - if (studentRegistration == null) - { - _applicationContext.StudentCourses.Add(new StudentCourse { StudentId = context.Entity.Id, CourseId = mandatoryCourse.Id }); - } + _applicationContext.StudentCourses.Add(new StudentCourse { StudentId = context.Entity.Id, CourseId = mandatoryCourse.Id }); } } } diff --git a/samples/3 - StudentManagerAspNetCore/ApplicationDbContext.cs b/samples/3 - StudentManagerAspNetCore/ApplicationDbContext.cs index 572fdec..a176d1f 100644 --- a/samples/3 - StudentManagerAspNetCore/ApplicationDbContext.cs +++ b/samples/3 - StudentManagerAspNetCore/ApplicationDbContext.cs @@ -1,33 +1,32 @@ using Microsoft.EntityFrameworkCore; -namespace StudentManager -{ +namespace StudentManager; + - public class ApplicationDbContext(DbContextOptions options) : DbContext(options) +public class ApplicationDbContext(DbContextOptions options) : DbContext(options) +{ + protected override void OnModelCreating(ModelBuilder modelBuilder) { - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity() - .HasKey(x => new { x.StudentId, x.CourseId }); + modelBuilder.Entity() + .HasKey(x => new { x.StudentId, x.CourseId }); - modelBuilder.Entity() - .HasKey(x => new { x.Discriminator, x.Id, x.RecordDate }); + modelBuilder.Entity() + .HasKey(x => new { x.Discriminator, x.Id, x.RecordDate }); - modelBuilder.Entity() - .HasQueryFilter(x => x.DeletedOn == null); + modelBuilder.Entity() + .HasQueryFilter(x => x.DeletedOn == null); - modelBuilder.Entity() - .HasQueryFilter(x => x.Course.DeletedOn == null); + modelBuilder.Entity() + .HasQueryFilter(x => x.Course.DeletedOn == null); - base.OnModelCreating(modelBuilder); - } + base.OnModelCreating(modelBuilder); + } - public DbSet Students { get; set; } + public DbSet Students { get; set; } - public DbSet Courses { get; set; } + public DbSet Courses { get; set; } - public DbSet StudentCourses { get; set; } + public DbSet StudentCourses { get; set; } - public DbSet Audits { get; set; } - } + public DbSet Audits { get; set; } } diff --git a/samples/3 - StudentManagerAspNetCore/Models.cs b/samples/3 - StudentManagerAspNetCore/Models.cs index 1211a03..56bca85 100644 --- a/samples/3 - StudentManagerAspNetCore/Models.cs +++ b/samples/3 - StudentManagerAspNetCore/Models.cs @@ -1,50 +1,49 @@ using StudentManager.Traits; -namespace StudentManager +namespace StudentManager; + +public class Student : ISoftDelete, IAudited { - public class Student : ISoftDelete, IAudited - { - public int Id { get; set; } + public int Id { get; set; } - public string DisplayName { get; set; } + public string DisplayName { get; set; } - public DateTimeOffset RegistrationDate { get; set; } + public DateTimeOffset RegistrationDate { get; set; } - public ICollection Courses { get; set; } + public ICollection Courses { get; set; } - public DateTimeOffset? DeletedOn { get; set; } - } + public DateTimeOffset? DeletedOn { get; set; } +} - public class Course : ISoftDelete, IAudited - { - public int Id { get; set; } +public class Course : ISoftDelete, IAudited +{ + public int Id { get; set; } - public string DisplayName { get; set; } + public string DisplayName { get; set; } - public bool IsMandatory { get; set; } + public bool IsMandatory { get; set; } - public DateTimeOffset? DeletedOn { get; set; } - } + public DateTimeOffset? DeletedOn { get; set; } +} - public class StudentCourse - { - public int StudentId { get; set; } +public class StudentCourse +{ + public int StudentId { get; set; } - public int CourseId { get; set; } + public int CourseId { get; set; } - public Student Student { get; set; } + public Student Student { get; set; } - public Course Course { get; set; } - } + public Course Course { get; set; } +} - public class Audit - { - public string Discriminator { get; set; } +public class Audit +{ + public string Discriminator { get; set; } - public int Id { get; set; } + public int Id { get; set; } - public DateTimeOffset RecordDate { get; set; } + public DateTimeOffset RecordDate { get; set; } - public string Record { get; set; } - } + public string Record { get; set; } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs index 2817fb7..761988b 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Audits/Index.cshtml.cs @@ -1,14 +1,13 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Pages +namespace StudentManager.Pages; + +public class AuditsModel(StudentManager.ApplicationDbContext context) : PageModel { - public class AuditsModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - public IList Audit { get; set; } + public IList Audit { get; set; } - public async Task OnGetAsync() => Audit = await _context.Audits.ToListAsync(); - } + public async Task OnGetAsync() => Audit = await _context.Audits.ToListAsync(); } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs index b034423..7673f3c 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Create.cshtml.cs @@ -1,30 +1,29 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace StudentManager.Pages.Courses +namespace StudentManager.Pages.Courses; + +public class CreateModel(StudentManager.ApplicationDbContext context) : PageModel { - public class CreateModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - public IActionResult OnGet() => Page(); + public IActionResult OnGet() => Page(); - [BindProperty] - public Course Course { get; set; } + [BindProperty] + public Course Course { get; set; } - // To protect from overposting attacks, enable the specific properties you want to bind to, for - // more details, see https://aka.ms/RazorPagesCRUD. - public async Task OnPostAsync() + // To protect from overposting attacks, enable the specific properties you want to bind to, for + // more details, see https://aka.ms/RazorPagesCRUD. + public async Task OnPostAsync() + { + if (!ModelState.IsValid) { - if (!ModelState.IsValid) - { - return Page(); - } + return Page(); + } - _context.Courses.Add(Course); - await _context.SaveChangesAsync(); + _context.Courses.Add(Course); + await _context.SaveChangesAsync(); - return RedirectToPage("./Index"); - } + return RedirectToPage("./Index"); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs index c0084b2..eb6d76a 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Delete.cshtml.cs @@ -2,47 +2,46 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Pages.Courses +namespace StudentManager.Pages.Courses; + +public class DeleteModel(StudentManager.ApplicationDbContext context) : PageModel { - public class DeleteModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - [BindProperty] - public Course Course { get; set; } + [BindProperty] + public Course Course { get; set; } - public async Task OnGetAsync(int? id) + public async Task OnGetAsync(int? id) + { + if (id == null) { - if (id == null) - { - return NotFound(); - } - - Course = await _context.Courses.FirstOrDefaultAsync(m => m.Id == id); - - if (Course == null) - { - return NotFound(); - } - return Page(); + return NotFound(); } - public async Task OnPostAsync(int? id) + Course = await _context.Courses.FirstOrDefaultAsync(m => m.Id == id); + + if (Course == null) { - if (id == null) - { - return NotFound(); - } + return NotFound(); + } + return Page(); + } - Course = await _context.Courses.FindAsync(id); + public async Task OnPostAsync(int? id) + { + if (id == null) + { + return NotFound(); + } - if (Course != null) - { - _context.Courses.Remove(Course); - await _context.SaveChangesAsync(); - } + Course = await _context.Courses.FindAsync(id); - return RedirectToPage("./Index"); + if (Course != null) + { + _context.Courses.Remove(Course); + await _context.SaveChangesAsync(); } + + return RedirectToPage("./Index"); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs index dac2a66..514c7ae 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Details.cshtml.cs @@ -2,28 +2,27 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Pages.Courses +namespace StudentManager.Pages.Courses; + +public class DetailsModel(StudentManager.ApplicationDbContext context) : PageModel { - public class DetailsModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - public Course Course { get; set; } + public Course Course { get; set; } - public async Task OnGetAsync(int? id) + public async Task OnGetAsync(int? id) + { + if (id == null) { - if (id == null) - { - return NotFound(); - } + return NotFound(); + } - Course = await _context.Courses.FirstOrDefaultAsync(m => m.Id == id); + Course = await _context.Courses.FirstOrDefaultAsync(m => m.Id == id); - if (Course == null) - { - return NotFound(); - } - return Page(); + if (Course == null) + { + return NotFound(); } + return Page(); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs index 71879cf..f501298 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Edit.cshtml.cs @@ -2,61 +2,60 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Pages.Courses +namespace StudentManager.Pages.Courses; + +public class EditModel(StudentManager.ApplicationDbContext context) : PageModel { - public class EditModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - [BindProperty] - public Course Course { get; set; } + [BindProperty] + public Course Course { get; set; } - public async Task OnGetAsync(int? id) + public async Task OnGetAsync(int? id) + { + if (id == null) { - if (id == null) - { - return NotFound(); - } + return NotFound(); + } - Course = await _context.Courses.FirstOrDefaultAsync(m => m.Id == id); + Course = await _context.Courses.FirstOrDefaultAsync(m => m.Id == id); - if (Course == null) - { - return NotFound(); - } - return Page(); + if (Course == null) + { + return NotFound(); } + return Page(); + } - // To protect from overposting attacks, enable the specific properties you want to bind to, for - // more details, see https://aka.ms/RazorPagesCRUD. - public async Task OnPostAsync() + // To protect from overposting attacks, enable the specific properties you want to bind to, for + // more details, see https://aka.ms/RazorPagesCRUD. + public async Task OnPostAsync() + { + if (!ModelState.IsValid) { - if (!ModelState.IsValid) - { - return Page(); - } + return Page(); + } - _context.Attach(Course).State = EntityState.Modified; + _context.Attach(Course).State = EntityState.Modified; - try + try + { + await _context.SaveChangesAsync(); + } + catch (DbUpdateConcurrencyException) + { + if (!CourseExists(Course.Id)) { - await _context.SaveChangesAsync(); + return NotFound(); } - catch (DbUpdateConcurrencyException) + else { - if (!CourseExists(Course.Id)) - { - return NotFound(); - } - else - { - throw; - } + throw; } - - return RedirectToPage("./Index"); } - private bool CourseExists(int id) => _context.Courses.Any(e => e.Id == id); + return RedirectToPage("./Index"); } + + private bool CourseExists(int id) => _context.Courses.Any(e => e.Id == id); } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs index b2c2add..3cfd2c4 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Courses/Index.cshtml.cs @@ -1,14 +1,13 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Pages.Courses +namespace StudentManager.Pages.Courses; + +public class IndexModel(StudentManager.ApplicationDbContext context) : PageModel { - public class IndexModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - public IList Course { get; set; } + public IList Course { get; set; } - public async Task OnGetAsync() => Course = await _context.Courses.IgnoreQueryFilters().ToListAsync(); - } + public async Task OnGetAsync() => Course = await _context.Courses.IgnoreQueryFilters().ToListAsync(); } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs index 73e3031..e576b52 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Error.cshtml.cs @@ -2,17 +2,16 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace StudentManager.Pages +namespace StudentManager.Pages; + +[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] +public class ErrorModel(ILogger logger) : PageModel { - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] - public class ErrorModel(ILogger logger) : PageModel - { - public string RequestId { get; set; } + public string RequestId { get; set; } - public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - private readonly ILogger _logger = logger; + private readonly ILogger _logger = logger; - public void OnGet() => RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; - } + public void OnGet() => RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs index 8a7bdda..d50cc3b 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Index.cshtml.cs @@ -1,14 +1,13 @@ using Microsoft.AspNetCore.Mvc.RazorPages; -namespace StudentManager.Pages +namespace StudentManager.Pages; + +public class IndexModel(ILogger logger) : PageModel { - public class IndexModel(ILogger logger) : PageModel - { - private readonly ILogger _logger = logger; + private readonly ILogger _logger = logger; - public void OnGet() - { + public void OnGet() + { - } } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs index 8844a34..aec8e32 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Create.cshtml.cs @@ -1,30 +1,29 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace StudentManager.Pages.Students +namespace StudentManager.Pages.Students; + +public class CreateModel(StudentManager.ApplicationDbContext context) : PageModel { - public class CreateModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - public IActionResult OnGet() => Page(); + public IActionResult OnGet() => Page(); - [BindProperty] - public Student Student { get; set; } + [BindProperty] + public Student Student { get; set; } - // To protect from overposting attacks, enable the specific properties you want to bind to, for - // more details, see https://aka.ms/RazorPagesCRUD. - public async Task OnPostAsync() + // To protect from overposting attacks, enable the specific properties you want to bind to, for + // more details, see https://aka.ms/RazorPagesCRUD. + public async Task OnPostAsync() + { + if (!ModelState.IsValid) { - if (!ModelState.IsValid) - { - return Page(); - } + return Page(); + } - _context.Students.Add(Student); - await _context.SaveChangesAsync(); + _context.Students.Add(Student); + await _context.SaveChangesAsync(); - return RedirectToPage("./Index"); - } + return RedirectToPage("./Index"); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs index 410945f..751a045 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Delete.cshtml.cs @@ -2,47 +2,46 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Pages.Students +namespace StudentManager.Pages.Students; + +public class DeleteModel(StudentManager.ApplicationDbContext context) : PageModel { - public class DeleteModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - [BindProperty] - public Student Student { get; set; } + [BindProperty] + public Student Student { get; set; } - public async Task OnGetAsync(int? id) + public async Task OnGetAsync(int? id) + { + if (id == null) { - if (id == null) - { - return NotFound(); - } - - Student = await _context.Students.FirstOrDefaultAsync(m => m.Id == id); - - if (Student == null) - { - return NotFound(); - } - return Page(); + return NotFound(); } - public async Task OnPostAsync(int? id) + Student = await _context.Students.FirstOrDefaultAsync(m => m.Id == id); + + if (Student == null) { - if (id == null) - { - return NotFound(); - } + return NotFound(); + } + return Page(); + } - Student = await _context.Students.FindAsync(id); + public async Task OnPostAsync(int? id) + { + if (id == null) + { + return NotFound(); + } - if (Student != null) - { - _context.Students.Remove(Student); - await _context.SaveChangesAsync(); - } + Student = await _context.Students.FindAsync(id); - return RedirectToPage("./Index"); + if (Student != null) + { + _context.Students.Remove(Student); + await _context.SaveChangesAsync(); } + + return RedirectToPage("./Index"); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs index ab0e003..53de921 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Details.cshtml.cs @@ -2,28 +2,27 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Pages.Students +namespace StudentManager.Pages.Students; + +public class DetailsModel(StudentManager.ApplicationDbContext context) : PageModel { - public class DetailsModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - public Student Student { get; set; } + public Student Student { get; set; } - public async Task OnGetAsync(int? id) + public async Task OnGetAsync(int? id) + { + if (id == null) { - if (id == null) - { - return NotFound(); - } + return NotFound(); + } - Student = await _context.Students.FirstOrDefaultAsync(m => m.Id == id); + Student = await _context.Students.FirstOrDefaultAsync(m => m.Id == id); - if (Student == null) - { - return NotFound(); - } - return Page(); + if (Student == null) + { + return NotFound(); } + return Page(); } } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs index ca983e2..c533301 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Edit.cshtml.cs @@ -2,61 +2,60 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Pages.Students +namespace StudentManager.Pages.Students; + +public class EditModel(StudentManager.ApplicationDbContext context) : PageModel { - public class EditModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - [BindProperty] - public Student Student { get; set; } + [BindProperty] + public Student Student { get; set; } - public async Task OnGetAsync(int? id) + public async Task OnGetAsync(int? id) + { + if (id == null) { - if (id == null) - { - return NotFound(); - } + return NotFound(); + } - Student = await _context.Students.FirstOrDefaultAsync(m => m.Id == id); + Student = await _context.Students.FirstOrDefaultAsync(m => m.Id == id); - if (Student == null) - { - return NotFound(); - } - return Page(); + if (Student == null) + { + return NotFound(); } + return Page(); + } - // To protect from overposting attacks, enable the specific properties you want to bind to, for - // more details, see https://aka.ms/RazorPagesCRUD. - public async Task OnPostAsync() + // To protect from overposting attacks, enable the specific properties you want to bind to, for + // more details, see https://aka.ms/RazorPagesCRUD. + public async Task OnPostAsync() + { + if (!ModelState.IsValid) { - if (!ModelState.IsValid) - { - return Page(); - } + return Page(); + } - _context.Attach(Student).State = EntityState.Modified; + _context.Attach(Student).State = EntityState.Modified; - try + try + { + await _context.SaveChangesAsync(); + } + catch (DbUpdateConcurrencyException) + { + if (!StudentExists(Student.Id)) { - await _context.SaveChangesAsync(); + return NotFound(); } - catch (DbUpdateConcurrencyException) + else { - if (!StudentExists(Student.Id)) - { - return NotFound(); - } - else - { - throw; - } + throw; } - - return RedirectToPage("./Index"); } - private bool StudentExists(int id) => _context.Students.Any(e => e.Id == id); + return RedirectToPage("./Index"); } + + private bool StudentExists(int id) => _context.Students.Any(e => e.Id == id); } diff --git a/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs b/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs index 0fac5ed..c6063e5 100644 --- a/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs +++ b/samples/3 - StudentManagerAspNetCore/Pages/Students/Index.cshtml.cs @@ -1,14 +1,13 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Pages.Students +namespace StudentManager.Pages.Students; + +public class IndexModel(StudentManager.ApplicationDbContext context) : PageModel { - public class IndexModel(StudentManager.ApplicationDbContext context) : PageModel - { - private readonly StudentManager.ApplicationDbContext _context = context; + private readonly StudentManager.ApplicationDbContext _context = context; - public IList Student { get; set; } + public IList Student { get; set; } - public async Task OnGetAsync() => Student = await _context.Students.Include(x => x.Courses).ThenInclude(x => x.Course).ToListAsync(); - } + public async Task OnGetAsync() => Student = await _context.Students.Include(x => x.Courses).ThenInclude(x => x.Course).ToListAsync(); } diff --git a/samples/3 - StudentManagerAspNetCore/Services/EmailService.cs b/samples/3 - StudentManagerAspNetCore/Services/EmailService.cs index 938aec3..5cef884 100644 --- a/samples/3 - StudentManagerAspNetCore/Services/EmailService.cs +++ b/samples/3 - StudentManagerAspNetCore/Services/EmailService.cs @@ -1,10 +1,9 @@ -namespace StudentManager.Services +namespace StudentManager.Services; + +public class EmailService { - public class EmailService + public void SendEmail(Student student, string message) { - public void SendEmail(Student student, string message) - { - // Left up for imagination - } + // Left up for imagination } } diff --git a/samples/3 - StudentManagerAspNetCore/Traits/IAudited.cs b/samples/3 - StudentManagerAspNetCore/Traits/IAudited.cs index 8c7829c..f23a4b4 100644 --- a/samples/3 - StudentManagerAspNetCore/Traits/IAudited.cs +++ b/samples/3 - StudentManagerAspNetCore/Traits/IAudited.cs @@ -1,7 +1,6 @@ -namespace StudentManager.Traits +namespace StudentManager.Traits; + +public interface IAudited { - public interface IAudited - { - public int Id { get; set; } - } + public int Id { get; set; } } diff --git a/samples/3 - StudentManagerAspNetCore/Traits/ISoftDelete.cs b/samples/3 - StudentManagerAspNetCore/Traits/ISoftDelete.cs index 5349046..5beaf2f 100644 --- a/samples/3 - StudentManagerAspNetCore/Traits/ISoftDelete.cs +++ b/samples/3 - StudentManagerAspNetCore/Traits/ISoftDelete.cs @@ -1,7 +1,6 @@ -namespace StudentManager.Traits +namespace StudentManager.Traits; + +public interface ISoftDelete { - public interface ISoftDelete - { - DateTimeOffset? DeletedOn { get; set; } - } + DateTimeOffset? DeletedOn { get; set; } } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs index f7d2437..c892594 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Courses/AutoSignupStudents.cs @@ -1,25 +1,24 @@ using EntityFrameworkCore.Triggered; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Triggers.Courses +namespace StudentManager.Triggers.Courses; + +public class AutoSignupStudents(ApplicationDbContext applicationContext) : IBeforeSaveAsyncTrigger { - public class AutoSignupStudents(ApplicationDbContext applicationContext) : IBeforeSaveAsyncTrigger - { - readonly ApplicationDbContext _applicationContext = applicationContext; + readonly ApplicationDbContext _applicationContext = applicationContext; - public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) + public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) + { + if (context.Entity.IsMandatory) { - if (context.Entity.IsMandatory) - { - // Fetch all students that are not yet signup up for this course - var students = await _applicationContext.Students - .Where(x => x.Courses.All(course => course.CourseId != context.Entity.Id)) - .ToListAsync(cancellationToken); + // Fetch all students that are not yet signup up for this course + var students = await _applicationContext.Students + .Where(x => x.Courses.All(course => course.CourseId != context.Entity.Id)) + .ToListAsync(cancellationToken); - foreach (var student in students) - { - _applicationContext.StudentCourses.Add(new StudentCourse { Student = student, Course = context.Entity }); - } + foreach (var student in students) + { + _applicationContext.StudentCourses.Add(new StudentCourse { Student = student, Course = context.Entity }); } } } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs index 5acb418..62164d2 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/BlockRemovalWhenCourseIsMandatory.cs @@ -1,20 +1,19 @@ using EntityFrameworkCore.Triggered; -namespace StudentManager.Triggers.StudentCourses +namespace StudentManager.Triggers.StudentCourses; + +public class BlockRemovalWhenCourseIsMandatory(ApplicationDbContext applicationContext) : IBeforeSaveAsyncTrigger { - public class BlockRemovalWhenCourseIsMandatory(ApplicationDbContext applicationContext) : IBeforeSaveAsyncTrigger - { - readonly ApplicationDbContext _applicationContext = applicationContext; + readonly ApplicationDbContext _applicationContext = applicationContext; - public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) + public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) + { + if (context.ChangeType == ChangeType.Deleted) { - if (context.ChangeType == ChangeType.Deleted) + var course = await _applicationContext.Courses.FindAsync([context.Entity.CourseId], cancellationToken); + if (course.IsMandatory) { - var course = await _applicationContext.Courses.FindAsync([context.Entity.CourseId], cancellationToken); - if (course.IsMandatory) - { - throw new InvalidOperationException("Course is required"); - } + throw new InvalidOperationException("Course is required"); } } } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs index abdb60f..50e1533 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/StudentCourses/SendWelcomingEmail.cs @@ -1,19 +1,18 @@ using EntityFrameworkCore.Triggered; using StudentManager.Services; -namespace StudentManager.Triggers.StudentCourses +namespace StudentManager.Triggers.StudentCourses; + +public class SendWelcomingEmail(ApplicationDbContext applicationContext, EmailService emailService) : IAfterSaveAsyncTrigger { - public class SendWelcomingEmail(ApplicationDbContext applicationContext, EmailService emailService) : IAfterSaveAsyncTrigger - { - readonly ApplicationDbContext _applicationContext = applicationContext; - readonly EmailService _emailService = emailService; + readonly ApplicationDbContext _applicationContext = applicationContext; + readonly EmailService _emailService = emailService; - public async Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) - { - var student = await _applicationContext.Students.FindAsync([context.Entity.StudentId], cancellationToken); - var course = await _applicationContext.Courses.FindAsync([context.Entity.CourseId], cancellationToken); + public async Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) + { + var student = await _applicationContext.Students.FindAsync([context.Entity.StudentId], cancellationToken); + var course = await _applicationContext.Courses.FindAsync([context.Entity.CourseId], cancellationToken); - _emailService.SendEmail(student, $"Welcoming {student.DisplayName} to the course: {course.DisplayName}"); - } + _emailService.SendEmail(student, $"Welcoming {student.DisplayName} to the course: {course.DisplayName}"); } } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs index 5026224..f861cb0 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Students/AssignRegistrationDate.cs @@ -1,9 +1,8 @@ using EntityFrameworkCore.Triggered; -namespace StudentManager.Triggers.Students +namespace StudentManager.Triggers.Students; + +public class AssignRegistrationDate : IBeforeSaveTrigger { - public class AssignRegistrationDate : IBeforeSaveTrigger - { - public void BeforeSave(ITriggerContext context) => context.Entity.RegistrationDate = DateTime.Today; - } + public void BeforeSave(ITriggerContext context) => context.Entity.RegistrationDate = DateTime.Today; } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs index 223ee18..ff6d5ee 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Students/SignupToMandatoryCourses.cs @@ -1,25 +1,24 @@ using EntityFrameworkCore.Triggered; using Microsoft.EntityFrameworkCore; -namespace StudentManager.Triggers.Students +namespace StudentManager.Triggers.Students; + +public class SignupToMandatoryCourses(ApplicationDbContext applicationContext) : IBeforeSaveAsyncTrigger { - public class SignupToMandatoryCourses(ApplicationDbContext applicationContext) : IBeforeSaveAsyncTrigger + readonly ApplicationDbContext _applicationContext = applicationContext; + + public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) { - readonly ApplicationDbContext _applicationContext = applicationContext; + var mandatoryCourses = await _applicationContext.Courses + .Where(x => x.IsMandatory) + .ToListAsync(cancellationToken); - public async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) + foreach (var mandatoryCourse in mandatoryCourses) { - var mandatoryCourses = await _applicationContext.Courses - .Where(x => x.IsMandatory) - .ToListAsync(cancellationToken); - - foreach (var mandatoryCourse in mandatoryCourses) + var studentRegistration = _applicationContext.StudentCourses.Find(context.Entity.Id, mandatoryCourse.Id); + if (studentRegistration == null) { - var studentRegistration = _applicationContext.StudentCourses.Find(context.Entity.Id, mandatoryCourse.Id); - if (studentRegistration == null) - { - _applicationContext.StudentCourses.Add(new StudentCourse { Student = context.Entity, Course = mandatoryCourse }); - } + _applicationContext.StudentCourses.Add(new StudentCourse { Student = context.Entity, Course = mandatoryCourse }); } } } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs index 846f9b3..5d795bc 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/Audited/CreateAuditRecord.cs @@ -2,32 +2,31 @@ using EntityFrameworkCore.Triggered; using StudentManager.Traits; -namespace StudentManager.Triggers.Traits.Audited -{ - public class CreateAuditRecord(ApplicationDbContext applicationContext) : IBeforeSaveTrigger - { - private readonly ApplicationDbContext _applicationContext = applicationContext; +namespace StudentManager.Triggers.Traits.Audited; - public void BeforeSave(ITriggerContext context) - { - var recordBuilder = new StringBuilder(); +public class CreateAuditRecord(ApplicationDbContext applicationContext) : IBeforeSaveTrigger +{ + private readonly ApplicationDbContext _applicationContext = applicationContext; - var changes = context.Entity.GetType() - .GetProperties() - .Select(property => (name: property.Name, oldValue: context.ChangeType != ChangeType.Added ? property.GetValue(context.UnmodifiedEntity) : null, newValue: property.GetValue(context.Entity))) - .Where(x => context.ChangeType == ChangeType.Added || x.newValue != x.oldValue); + public void BeforeSave(ITriggerContext context) + { + var recordBuilder = new StringBuilder(); - foreach (var change in changes) - { - recordBuilder.AppendLine($"{change.name}: {change.oldValue ?? "null"} => {change.newValue ?? "null"}"); - } + var changes = context.Entity.GetType() + .GetProperties() + .Select(property => (name: property.Name, oldValue: context.ChangeType != ChangeType.Added ? property.GetValue(context.UnmodifiedEntity) : null, newValue: property.GetValue(context.Entity))) + .Where(x => context.ChangeType == ChangeType.Added || x.newValue != x.oldValue); - _applicationContext.Audits.Add(new Audit { - Id = context.Entity.Id, - Discriminator = context.Entity.GetType().Name, - RecordDate = DateTimeOffset.Now, - Record = recordBuilder.ToString() - }); + foreach (var change in changes) + { + recordBuilder.AppendLine($"{change.name}: {change.oldValue ?? "null"} => {change.newValue ?? "null"}"); } + + _applicationContext.Audits.Add(new Audit { + Id = context.Entity.Id, + Discriminator = context.Entity.GetType().Name, + RecordDate = DateTimeOffset.Now, + Record = recordBuilder.ToString() + }); } } diff --git a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs index ec67469..2dce02e 100644 --- a/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs +++ b/samples/3 - StudentManagerAspNetCore/Triggers/Traits/SoftDelete/EnsureSoftDelete.cs @@ -1,19 +1,18 @@ using EntityFrameworkCore.Triggered; using StudentManager.Traits; -namespace StudentManager.Triggers.Traits.SoftDelete +namespace StudentManager.Triggers.Traits.SoftDelete; + +class EnsureSoftDelete(ApplicationDbContext applicationContext) : IBeforeSaveTrigger { - class EnsureSoftDelete(ApplicationDbContext applicationContext) : IBeforeSaveTrigger - { - readonly ApplicationDbContext _applicationContext = applicationContext; + readonly ApplicationDbContext _applicationContext = applicationContext; - public void BeforeSave(ITriggerContext context) + public void BeforeSave(ITriggerContext context) + { + if (context.ChangeType == ChangeType.Deleted) { - if (context.ChangeType == ChangeType.Deleted) - { - context.Entity.DeletedOn = DateTimeOffset.Now; - _applicationContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; - } + context.Entity.DeletedOn = DateTimeOffset.Now; + _applicationContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; } } } diff --git a/samples/4 - BlazorTests/ApplicationDbContext.cs b/samples/4 - BlazorTests/ApplicationDbContext.cs index 4674726..ddb65c2 100644 --- a/samples/4 - BlazorTests/ApplicationDbContext.cs +++ b/samples/4 - BlazorTests/ApplicationDbContext.cs @@ -1,16 +1,15 @@ using Microsoft.EntityFrameworkCore; -namespace BlazorTests +namespace BlazorTests; + +public class Count { - public class Count - { - public Guid Id { get; set; } - public DateTime CreatedOn { get; set; } - } + public Guid Id { get; set; } + public DateTime CreatedOn { get; set; } +} - public class ApplicationDbContext(DbContextOptions options) : DbContext(options) - { - public DbSet Counts { get; set; } +public class ApplicationDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Counts { get; set; } - } } diff --git a/samples/4 - BlazorTests/Data/WeatherForecast.cs b/samples/4 - BlazorTests/Data/WeatherForecast.cs index 8fc963e..978c6b3 100644 --- a/samples/4 - BlazorTests/Data/WeatherForecast.cs +++ b/samples/4 - BlazorTests/Data/WeatherForecast.cs @@ -1,13 +1,12 @@ -namespace BlazorTests.Data +namespace BlazorTests.Data; + +public class WeatherForecast { - public class WeatherForecast - { - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public int TemperatureC { get; set; } + public int TemperatureC { get; set; } - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - public string Summary { get; set; } - } + public string Summary { get; set; } } diff --git a/samples/4 - BlazorTests/Data/WeatherForecastService.cs b/samples/4 - BlazorTests/Data/WeatherForecastService.cs index 79006ed..b61a54d 100644 --- a/samples/4 - BlazorTests/Data/WeatherForecastService.cs +++ b/samples/4 - BlazorTests/Data/WeatherForecastService.cs @@ -1,20 +1,19 @@ -namespace BlazorTests.Data +namespace BlazorTests.Data; + +public class WeatherForecastService { - public class WeatherForecastService - { - private readonly static string[] Summaries = - [ - "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" - ]; + private readonly static string[] Summaries = + [ + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + ]; - public Task GetForecastAsync(DateTime startDate) - { - var rng = new Random(); - return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { - Date = startDate.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] - }).ToArray()); - } + public Task GetForecastAsync(DateTime startDate) + { + var rng = new Random(); + return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { + Date = startDate.AddDays(index), + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] + }).ToArray()); } } diff --git a/samples/4 - BlazorTests/EventAggregator.cs b/samples/4 - BlazorTests/EventAggregator.cs index c7c8a94..23dd55d 100644 --- a/samples/4 - BlazorTests/EventAggregator.cs +++ b/samples/4 - BlazorTests/EventAggregator.cs @@ -1,12 +1,11 @@ -namespace BlazorTests +namespace BlazorTests; + +/// +/// This is NOT a production ready EventAggregator and only used for demo purposes +/// +public class EventAggregator { - /// - /// This is NOT a production ready EventAggregator and only used for demo purposes - /// - public class EventAggregator - { - public event Action CountAdded; + public event Action CountAdded; - public void PublishCountAdded(Count count) => CountAdded?.Invoke(count); - } + public void PublishCountAdded(Count count) => CountAdded?.Invoke(count); } diff --git a/samples/4 - BlazorTests/Pages/Error.cshtml.cs b/samples/4 - BlazorTests/Pages/Error.cshtml.cs index 087fda3..32100f1 100644 --- a/samples/4 - BlazorTests/Pages/Error.cshtml.cs +++ b/samples/4 - BlazorTests/Pages/Error.cshtml.cs @@ -2,18 +2,17 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace BlazorTests.Pages +namespace BlazorTests.Pages; + +[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] +[IgnoreAntiforgeryToken] +public class ErrorModel(ILogger logger) : PageModel { - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] - [IgnoreAntiforgeryToken] - public class ErrorModel(ILogger logger) : PageModel - { - public string RequestId { get; set; } + public string RequestId { get; set; } - public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - private readonly ILogger _logger = logger; + private readonly ILogger _logger = logger; - public void OnGet() => RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; - } + public void OnGet() => RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } diff --git a/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs b/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs index 8e08e6d..988b55e 100644 --- a/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs +++ b/samples/4 - BlazorTests/Triggers/Counts/PublishCountAddedEvent.cs @@ -1,17 +1,16 @@ using EntityFrameworkCore.Triggered; -namespace BlazorTests.Triggers.Counts +namespace BlazorTests.Triggers.Counts; + +public class PublishCountAddedEvent(EventAggregator eventAggregator) : IAfterSaveTrigger { - public class PublishCountAddedEvent(EventAggregator eventAggregator) : IAfterSaveTrigger - { - private readonly EventAggregator _eventAggregator = eventAggregator; + private readonly EventAggregator _eventAggregator = eventAggregator; - public void AfterSave(ITriggerContext context) + public void AfterSave(ITriggerContext context) + { + if (context.ChangeType == ChangeType.Added) { - if (context.ChangeType == ChangeType.Added) - { - _eventAggregator.PublishCountAdded(context.Entity); - } + _eventAggregator.PublishCountAdded(context.Entity); } } } diff --git a/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs b/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs index ad60d1c..f70306c 100644 --- a/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs +++ b/samples/4 - BlazorTests/Triggers/Counts/SetCreatedOn.cs @@ -1,9 +1,8 @@ using EntityFrameworkCore.Triggered; -namespace BlazorTests.Triggers.Counts +namespace BlazorTests.Triggers.Counts; + +public class SetCreatedOn : IBeforeSaveTrigger { - public class SetCreatedOn : IBeforeSaveTrigger - { - public void BeforeSave(ITriggerContext context) => context.Entity.CreatedOn = DateTime.UtcNow; - } + public void BeforeSave(ITriggerContext context) => context.Entity.CreatedOn = DateTime.UtcNow; } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/ChangeType.cs b/src/EntityFrameworkCore.Triggered.Abstractions/ChangeType.cs index 0d63e68..f979d4d 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/ChangeType.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/ChangeType.cs @@ -1,9 +1,8 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public enum ChangeType { - public enum ChangeType - { - Added, - Modified, - Deleted - } + Added, + Modified, + Deleted } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/CommonTriggerPriorities.cs b/src/EntityFrameworkCore.Triggered.Abstractions/CommonTriggerPriorities.cs index 163edba..2f77a4b 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/CommonTriggerPriorities.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/CommonTriggerPriorities.cs @@ -1,12 +1,11 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Intended public constants")] +public static class CommonTriggerPriority { - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Intended public constants")] - public static class CommonTriggerPriority - { - public const int Earlier = -2; - public const int Early = -1; - public const int Normal = 0; - public const int Late = 1; - public const int Later = 2; - } + public const int Earlier = -2; + public const int Early = -1; + public const int Normal = 0; + public const int Late = 1; + public const int Later = 2; } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveAsyncTrigger.cs index ddd5291..8fa9687 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveAsyncTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public interface IAfterSaveAsyncTrigger + where TEntity : class { - public interface IAfterSaveAsyncTrigger - where TEntity : class - { - Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken); - } + Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedAsyncTrigger.cs index cd3c30d..d38698f 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedAsyncTrigger.cs @@ -1,10 +1,7 @@ -namespace EntityFrameworkCore.Triggered -{ - public interface IAfterSaveFailedAsyncTrigger - where TEntity : class - { - Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken); - } - +namespace EntityFrameworkCore.Triggered; +public interface IAfterSaveFailedAsyncTrigger + where TEntity : class +{ + Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedTrigger.cs index 68c5b41..1bf0ec9 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveFailedTrigger.cs @@ -1,10 +1,7 @@ -namespace EntityFrameworkCore.Triggered -{ - public interface IAfterSaveFailedTrigger - where TEntity : class - { - void AfterSaveFailed(ITriggerContext context, Exception exception); - } - +namespace EntityFrameworkCore.Triggered; +public interface IAfterSaveFailedTrigger + where TEntity : class +{ + void AfterSaveFailed(ITriggerContext context, Exception exception); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveTrigger.cs index e0ff610..b7d9ba4 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IAfterSaveTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public interface IAfterSaveTrigger + where TEntity : class { - public interface IAfterSaveTrigger - where TEntity : class - { - void AfterSave(ITriggerContext context); - } + void AfterSave(ITriggerContext context); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveAsyncTrigger.cs index 8580510..85977a5 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveAsyncTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public interface IBeforeSaveAsyncTrigger + where TEntity : class { - public interface IBeforeSaveAsyncTrigger - where TEntity : class - { - Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken); - } + Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveTrigger.cs index 629113e..f4a0df3 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/IBeforeSaveTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public interface IBeforeSaveTrigger + where TEntity : class { - public interface IBeforeSaveTrigger - where TEntity : class - { - void BeforeSave(ITriggerContext context); - } + void BeforeSave(ITriggerContext context); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerContext.cs b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerContext.cs index 8dc280f..165394f 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerContext.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerContext.cs @@ -1,26 +1,25 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public interface ITriggerContext + where TEntity : class { - public interface ITriggerContext - where TEntity : class - { - /// - /// The type of change that caused this trigger to be raised - /// - ChangeType ChangeType { get; } + /// + /// The type of change that caused this trigger to be raised + /// + ChangeType ChangeType { get; } - /// - /// The entity that caused this trigger to be raised - /// - TEntity Entity { get; } + /// + /// The entity that caused this trigger to be raised + /// + TEntity Entity { get; } - /// - /// This will retain the unmodified entity in case when the ChangeType is Modified - /// - TEntity? UnmodifiedEntity { get; } + /// + /// This will retain the unmodified entity in case when the ChangeType is Modified + /// + TEntity? UnmodifiedEntity { get; } - /// - /// Gets or sets a key/value collection that can be used to share data within the scope of this Entity - /// - IDictionary Items { get; } - } + /// + /// Gets or sets a key/value collection that can be used to share data within the scope of this Entity + /// + IDictionary Items { get; } } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerPriority.cs b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerPriority.cs index 38c2c9d..35037c8 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerPriority.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerPriority.cs @@ -1,10 +1,9 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public interface ITriggerPriority { - public interface ITriggerPriority - { - /// - /// Get the priority number (lower means earlier) for when this trigger is supposed to be invoked - /// - public int Priority { get; } - } + /// + /// Get the priority number (lower means earlier) for when this trigger is supposed to be invoked + /// + public int Priority { get; } } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerSession.cs b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerSession.cs index 46e5d93..7a04868 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerSession.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/ITriggerSession.cs @@ -1,60 +1,59 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public interface ITriggerSession : IDisposable { - public interface ITriggerSession : IDisposable - { - /// - /// Discoveres any new pending changes in the DbContext - /// - void DiscoverChanges(); - void RaiseBeforeSaveStartingTriggers(); - void RaiseBeforeSaveCompletedTriggers(); - void RaiseAfterSaveFailedStartingTriggers(Exception exception); - void RaiseAfterSaveFailedCompletedTriggers(Exception exception); - void RaiseAfterSaveStartingTriggers(); - void RaiseAfterSaveCompletedTriggers(); - Task RaiseBeforeSaveStartingAsyncTriggers(CancellationToken cancellationToken = default); - Task RaiseBeforeSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default); - Task RaiseAfterSaveFailedStartingAsyncTriggers(Exception exception, CancellationToken cancellationToken = default); - Task RaiseAfterSaveFailedCompletedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default); - Task RaiseAfterSaveStartingAsyncTriggers(CancellationToken cancellationToken = default); - Task RaiseAfterSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default); - /// - /// Makes a snapshot of all changes in the DbContext and invokes BeforeSaveTriggers while detecting and cascading based on the cascade settings until all changes have been processed - /// - void RaiseBeforeSaveTriggers(); - /// - /// Makes a snapshot of all changes in the DbContext and invokes BeforeSaveTriggers while detecting and cascading based on the cascade settings until all changes have been processed - /// - Task RaiseBeforeSaveAsyncTriggers(CancellationToken cancellationToken = default); - /// - /// Makes a snapshot of all changes in the DbContext and invokes BeforeSaveTriggers while detecting and cascading based on the cascade settings until all changes have been processed - /// - /// Allows BeforeSaveTriggers not to include previously detected changes. Only new changes will be detected and fired upon. This is useful in case of multiple calls to RaiseBeforeSaveTriggers - void RaiseBeforeSaveTriggers(bool skipDetectedChanges); - /// - /// Makes a snapshot of all changes in the DbContext and invokes BeforeSaveTriggers while detecting and cascading based on the cascade settings until all changes have been processed - /// - /// Allows BeforeSaveTriggers not to include previously detected changes. Only new changes will be detected and fired upon. This is useful in case of multiple calls to RaiseBeforeSaveTriggers - Task RaiseBeforeSaveAsyncTriggers(bool skipDetectedChanges, CancellationToken cancellationToken = default); - /// - /// Captures and locks all discovered changes - /// - void CaptureDiscoveredChanges(); - /// - /// Invokes AfterSaveTriggers. Calling this method expects that either RaiseBeforeSaveTriggers() or DiscoverChanges() has been called - /// - void RaiseAfterSaveTriggers(); - /// - /// Invokes AfterSaveTriggers. Calling this method expects that either RaiseBeforeSaveTriggers() or DiscoverChanges() has been called - /// - Task RaiseAfterSaveAsyncTriggers(CancellationToken cancellationToken = default); - /// - /// Invokes AfterSaveFailedTriggers. Calling this method expects that either RaiseBeforeSaveTriggers() or DiscoverChanges() has been called - /// - void RaiseAfterSaveFailedTriggers(Exception exception); - /// - /// Invokes AfterSaveFailedTriggers. Calling this method expects that either RaiseBeforeSaveTriggers() or DiscoverChanges() has been called - /// - Task RaiseAfterSaveFailedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default); - } + /// + /// Discoveres any new pending changes in the DbContext + /// + void DiscoverChanges(); + void RaiseBeforeSaveStartingTriggers(); + void RaiseBeforeSaveCompletedTriggers(); + void RaiseAfterSaveFailedStartingTriggers(Exception exception); + void RaiseAfterSaveFailedCompletedTriggers(Exception exception); + void RaiseAfterSaveStartingTriggers(); + void RaiseAfterSaveCompletedTriggers(); + Task RaiseBeforeSaveStartingAsyncTriggers(CancellationToken cancellationToken = default); + Task RaiseBeforeSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default); + Task RaiseAfterSaveFailedStartingAsyncTriggers(Exception exception, CancellationToken cancellationToken = default); + Task RaiseAfterSaveFailedCompletedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default); + Task RaiseAfterSaveStartingAsyncTriggers(CancellationToken cancellationToken = default); + Task RaiseAfterSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default); + /// + /// Makes a snapshot of all changes in the DbContext and invokes BeforeSaveTriggers while detecting and cascading based on the cascade settings until all changes have been processed + /// + void RaiseBeforeSaveTriggers(); + /// + /// Makes a snapshot of all changes in the DbContext and invokes BeforeSaveTriggers while detecting and cascading based on the cascade settings until all changes have been processed + /// + Task RaiseBeforeSaveAsyncTriggers(CancellationToken cancellationToken = default); + /// + /// Makes a snapshot of all changes in the DbContext and invokes BeforeSaveTriggers while detecting and cascading based on the cascade settings until all changes have been processed + /// + /// Allows BeforeSaveTriggers not to include previously detected changes. Only new changes will be detected and fired upon. This is useful in case of multiple calls to RaiseBeforeSaveTriggers + void RaiseBeforeSaveTriggers(bool skipDetectedChanges); + /// + /// Makes a snapshot of all changes in the DbContext and invokes BeforeSaveTriggers while detecting and cascading based on the cascade settings until all changes have been processed + /// + /// Allows BeforeSaveTriggers not to include previously detected changes. Only new changes will be detected and fired upon. This is useful in case of multiple calls to RaiseBeforeSaveTriggers + Task RaiseBeforeSaveAsyncTriggers(bool skipDetectedChanges, CancellationToken cancellationToken = default); + /// + /// Captures and locks all discovered changes + /// + void CaptureDiscoveredChanges(); + /// + /// Invokes AfterSaveTriggers. Calling this method expects that either RaiseBeforeSaveTriggers() or DiscoverChanges() has been called + /// + void RaiseAfterSaveTriggers(); + /// + /// Invokes AfterSaveTriggers. Calling this method expects that either RaiseBeforeSaveTriggers() or DiscoverChanges() has been called + /// + Task RaiseAfterSaveAsyncTriggers(CancellationToken cancellationToken = default); + /// + /// Invokes AfterSaveFailedTriggers. Calling this method expects that either RaiseBeforeSaveTriggers() or DiscoverChanges() has been called + /// + void RaiseAfterSaveFailedTriggers(Exception exception); + /// + /// Invokes AfterSaveFailedTriggers. Calling this method expects that either RaiseBeforeSaveTriggers() or DiscoverChanges() has been called + /// + Task RaiseAfterSaveFailedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedAsyncTrigger.cs index 1efcef7..1c02b18 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IAfterSaveCompletedAsyncTrigger { - public interface IAfterSaveCompletedAsyncTrigger - { - Task AfterSaveCompletedAsync(CancellationToken cancellationToken); - } + Task AfterSaveCompletedAsync(CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedTrigger.cs index 86a7fcf..4ac7b35 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveCompletedTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IAfterSaveCompletedTrigger { - public interface IAfterSaveCompletedTrigger - { - void AfterSaveCompleted(); - } + void AfterSaveCompleted(); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedAsyncTrigger.cs index 8e08b0e..0ff1391 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IAfterSaveFailedCompletedAsyncTrigger { - public interface IAfterSaveFailedCompletedAsyncTrigger - { - Task AfterSaveFailedCompletedAsync(Exception exception, CancellationToken cancellationToken); - } + Task AfterSaveFailedCompletedAsync(Exception exception, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedTrigger.cs index 9fa24a5..a7075a2 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedCompletedTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IAfterSaveFailedCompletedTrigger { - public interface IAfterSaveFailedCompletedTrigger - { - void AfterSaveFailedCompleted(Exception exception); - } + void AfterSaveFailedCompleted(Exception exception); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingAsyncTrigger.cs index 91aa0b9..063cad1 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IAfterSaveFailedStartingAsyncTrigger { - public interface IAfterSaveFailedStartingAsyncTrigger - { - Task AfterSaveFailedStartingAsync(Exception exception, CancellationToken cancellationToken); - } + Task AfterSaveFailedStartingAsync(Exception exception, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingTrigger.cs index a25a1d5..5f7f559 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveFailedStartingTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IAfterSaveFailedStartingTrigger { - public interface IAfterSaveFailedStartingTrigger - { - void AfterSaveFailedStarting(Exception exception); - } + void AfterSaveFailedStarting(Exception exception); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingAsyncTrigger.cs index 7c743ea..36b6a5f 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IAfterSaveStartingAsyncTrigger { - public interface IAfterSaveStartingAsyncTrigger - { - Task AfterSaveStartingAsync(CancellationToken cancellationToken); - } + Task AfterSaveStartingAsync(CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingTrigger.cs index 8b281ff..ebcbfcf 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IAfterSaveStartingTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IAfterSaveStartingTrigger { - public interface IAfterSaveStartingTrigger - { - void AfterSaveStarting(); - } + void AfterSaveStarting(); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedAsyncTrigger.cs index d13a84d..ce3c2d1 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IBeforeSaveCompletedAsyncTrigger { - public interface IBeforeSaveCompletedAsyncTrigger - { - Task BeforeSaveCompletedAsync(CancellationToken cancellationToken); - } + Task BeforeSaveCompletedAsync(CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedTrigger.cs index 304a8d2..1459795 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveCompletedTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IBeforeSaveCompletedTrigger { - public interface IBeforeSaveCompletedTrigger - { - void BeforeSaveCompleted(); - } + void BeforeSaveCompleted(); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingAsyncTrigger.cs index 2fee7cb..7217aa5 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IBeforeSaveStartingAsyncTrigger { - public interface IBeforeSaveStartingAsyncTrigger - { - Task BeforeSaveStartingAsync(CancellationToken cancellationToken); - } + Task BeforeSaveStartingAsync(CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingTrigger.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingTrigger.cs index 7e6ab2c..f9e543d 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/Lifecycles/IBeforeSaveStartingTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Lifecycles +namespace EntityFrameworkCore.Triggered.Lifecycles; + +public interface IBeforeSaveStartingTrigger { - public interface IBeforeSaveStartingTrigger - { - void BeforeSaveStarting(); - } + void BeforeSaveStarting(); } diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/TriggerSessionConfiguration.cs b/src/EntityFrameworkCore.Triggered.Abstractions/TriggerSessionConfiguration.cs index 07f3ee6..705fb3b 100644 --- a/src/EntityFrameworkCore.Triggered.Abstractions/TriggerSessionConfiguration.cs +++ b/src/EntityFrameworkCore.Triggered.Abstractions/TriggerSessionConfiguration.cs @@ -1,15 +1,14 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public record TriggerSessionConfiguration { - public record TriggerSessionConfiguration + public TriggerSessionConfiguration(bool disabled, int maxCascadeCycles) { - public TriggerSessionConfiguration(bool disabled, int maxCascadeCycles) - { - Disabled = disabled; - MaxCascadeCycles = maxCascadeCycles; - } + Disabled = disabled; + MaxCascadeCycles = maxCascadeCycles; + } - public bool Disabled { get; init; } + public bool Disabled { get; init; } - public int MaxCascadeCycles { get; init; } - } + public int MaxCascadeCycles { get; init; } } diff --git a/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs b/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs index 9e1a833..a1881da 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/ServiceCollectionExtensions.cs @@ -4,107 +4,106 @@ using EntityFrameworkCore.Triggered.Lifecycles; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace Microsoft.Extensions.DependencyInjection +namespace Microsoft.Extensions.DependencyInjection; + +public static class ServiceCollectionExtensions { - public static class ServiceCollectionExtensions + readonly static Type[] _wellKnownTriggerTypes = [ + typeof(IBeforeSaveTrigger<>), + typeof(IBeforeSaveAsyncTrigger<>), + typeof(IAfterSaveTrigger<>), + typeof(IAfterSaveAsyncTrigger<>), + typeof(IAfterSaveFailedTrigger<>), + typeof(IAfterSaveFailedAsyncTrigger<>), + typeof(IBeforeSaveStartingTrigger), + typeof(IBeforeSaveStartingAsyncTrigger), + typeof(IBeforeSaveCompletedTrigger), + typeof(IBeforeSaveCompletedAsyncTrigger), + typeof(IAfterSaveFailedStartingTrigger), + typeof(IAfterSaveFailedStartingAsyncTrigger), + typeof(IAfterSaveFailedCompletedTrigger), + typeof(IAfterSaveFailedCompletedAsyncTrigger), + typeof(IAfterSaveStartingTrigger), + typeof(IAfterSaveStartingAsyncTrigger), + typeof(IAfterSaveCompletedTrigger), + typeof(IAfterSaveCompletedAsyncTrigger) + ]; + + static void RegisterTriggerTypes(Type triggerImplementationType, IServiceCollection services) { - readonly static Type[] _wellKnownTriggerTypes = [ - typeof(IBeforeSaveTrigger<>), - typeof(IBeforeSaveAsyncTrigger<>), - typeof(IAfterSaveTrigger<>), - typeof(IAfterSaveAsyncTrigger<>), - typeof(IAfterSaveFailedTrigger<>), - typeof(IAfterSaveFailedAsyncTrigger<>), - typeof(IBeforeSaveStartingTrigger), - typeof(IBeforeSaveStartingAsyncTrigger), - typeof(IBeforeSaveCompletedTrigger), - typeof(IBeforeSaveCompletedAsyncTrigger), - typeof(IAfterSaveFailedStartingTrigger), - typeof(IAfterSaveFailedStartingAsyncTrigger), - typeof(IAfterSaveFailedCompletedTrigger), - typeof(IAfterSaveFailedCompletedAsyncTrigger), - typeof(IAfterSaveStartingTrigger), - typeof(IAfterSaveStartingAsyncTrigger), - typeof(IAfterSaveCompletedTrigger), - typeof(IAfterSaveCompletedAsyncTrigger) - ]; - - static void RegisterTriggerTypes(Type triggerImplementationType, IServiceCollection services) + foreach (var customTriggerType in _wellKnownTriggerTypes) { - foreach (var customTriggerType in _wellKnownTriggerTypes) - { - var customTriggers = customTriggerType.IsGenericTypeDefinition + var customTriggers = customTriggerType.IsGenericTypeDefinition #pragma warning disable EF1001 // Internal EF Core API usage. - ? TypeHelpers.FindGenericInterfaces(triggerImplementationType, customTriggerType) + ? TypeHelpers.FindGenericInterfaces(triggerImplementationType, customTriggerType) #pragma warning restore EF1001 // Internal EF Core API usage. - : triggerImplementationType.GetInterfaces().Where(x => x == customTriggerType); + : triggerImplementationType.GetInterfaces().Where(x => x == customTriggerType); - foreach (var customTrigger in customTriggers) - { - services.Add(new ServiceDescriptor(customTrigger, sp => sp.GetRequiredService(triggerImplementationType), ServiceLifetime.Transient)); ; - } + foreach (var customTrigger in customTriggers) + { + services.Add(new ServiceDescriptor(customTrigger, sp => sp.GetRequiredService(triggerImplementationType), ServiceLifetime.Transient)); ; } } + } - public static IServiceCollection AddTrigger(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Scoped) - where TTrigger : class - { - services.TryAdd(new ServiceDescriptor(typeof(TTrigger), typeof(TTrigger), lifetime)); + public static IServiceCollection AddTrigger(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Scoped) + where TTrigger : class + { + services.TryAdd(new ServiceDescriptor(typeof(TTrigger), typeof(TTrigger), lifetime)); - RegisterTriggerTypes(typeof(TTrigger), services); + RegisterTriggerTypes(typeof(TTrigger), services); - return services; - } + return services; + } - public static IServiceCollection AddTrigger(this IServiceCollection services, object triggerInstance) - { - services.TryAddSingleton(triggerInstance); + public static IServiceCollection AddTrigger(this IServiceCollection services, object triggerInstance) + { + services.TryAddSingleton(triggerInstance); - RegisterTriggerTypes(triggerInstance.GetType(), services); + RegisterTriggerTypes(triggerInstance.GetType(), services); - return services; - } + return services; + } - public static IServiceCollection AddAssemblyTriggers(this IServiceCollection services) - => AddAssemblyTriggers(services, Assembly.GetCallingAssembly()); + public static IServiceCollection AddAssemblyTriggers(this IServiceCollection services) + => AddAssemblyTriggers(services, Assembly.GetCallingAssembly()); - public static IServiceCollection AddAssemblyTriggers(this IServiceCollection services, ServiceLifetime lifetime) - => AddAssemblyTriggers(services, lifetime, Assembly.GetCallingAssembly()); + public static IServiceCollection AddAssemblyTriggers(this IServiceCollection services, ServiceLifetime lifetime) + => AddAssemblyTriggers(services, lifetime, Assembly.GetCallingAssembly()); - public static IServiceCollection AddAssemblyTriggers(this IServiceCollection services, params Assembly[] assemblies) - => AddAssemblyTriggers(services, ServiceLifetime.Scoped, assemblies); + public static IServiceCollection AddAssemblyTriggers(this IServiceCollection services, params Assembly[] assemblies) + => AddAssemblyTriggers(services, ServiceLifetime.Scoped, assemblies); - public static IServiceCollection AddAssemblyTriggers(this IServiceCollection services, ServiceLifetime lifetime, params Assembly[] assemblies) - { - ArgumentNullException.ThrowIfNull(assemblies); + public static IServiceCollection AddAssemblyTriggers(this IServiceCollection services, ServiceLifetime lifetime, params Assembly[] assemblies) + { + ArgumentNullException.ThrowIfNull(assemblies); - var assemblyTypes = assemblies - .SelectMany(x => x.GetTypes()) - .Where(x => x.IsClass) - .Where(x => !x.IsAbstract); + var assemblyTypes = assemblies + .SelectMany(x => x.GetTypes()) + .Where(x => x.IsClass) + .Where(x => !x.IsAbstract); - foreach (var assemblyType in assemblyTypes) - { - var triggerTypes = assemblyType - .GetInterfaces() - .Where(x => _wellKnownTriggerTypes.Contains(x.IsConstructedGenericType ? x.GetGenericTypeDefinition() : x)); + foreach (var assemblyType in assemblyTypes) + { + var triggerTypes = assemblyType + .GetInterfaces() + .Where(x => _wellKnownTriggerTypes.Contains(x.IsConstructedGenericType ? x.GetGenericTypeDefinition() : x)); - var registered = false; + var registered = false; - foreach (var triggerType in triggerTypes) + foreach (var triggerType in triggerTypes) + { + if (!registered) { - if (!registered) - { - services.TryAdd(new ServiceDescriptor(assemblyType, assemblyType, lifetime)); - - registered = true; - } + services.TryAdd(new ServiceDescriptor(assemblyType, assemblyType, lifetime)); - services.Add(new ServiceDescriptor(triggerType, sp => sp.GetRequiredService(assemblyType), ServiceLifetime.Transient)); + registered = true; } - } - return services; + services.Add(new ServiceDescriptor(triggerType, sp => sp.GetRequiredService(assemblyType), ServiceLifetime.Transient)); + } } + + return services; } } diff --git a/src/EntityFrameworkCore.Triggered.Extensions/Trigger.cs b/src/EntityFrameworkCore.Triggered.Extensions/Trigger.cs index 9d01459..d91e154 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/Trigger.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/Trigger.cs @@ -1,20 +1,19 @@ -namespace EntityFrameworkCore.Triggered.Extensions -{ - public class Trigger : - IBeforeSaveTrigger, - IBeforeSaveAsyncTrigger, - IAfterSaveTrigger, - IAfterSaveAsyncTrigger, - IAfterSaveFailedTrigger, - IAfterSaveFailedAsyncTrigger +namespace EntityFrameworkCore.Triggered.Extensions; + +public class Trigger : + IBeforeSaveTrigger, + IBeforeSaveAsyncTrigger, + IAfterSaveTrigger, + IAfterSaveAsyncTrigger, + IAfterSaveFailedTrigger, + IAfterSaveFailedAsyncTrigger - where TEntity : class - { - public virtual void BeforeSave(ITriggerContext context) { } - public virtual void AfterSave(ITriggerContext context) { } - public virtual void AfterSaveFailed(ITriggerContext context, Exception exception) { } - public virtual Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => Task.CompletedTask; - public virtual Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => Task.CompletedTask; - public virtual Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken) => Task.CompletedTask; - } + where TEntity : class +{ + public virtual void BeforeSave(ITriggerContext context) { } + public virtual void AfterSave(ITriggerContext context) { } + public virtual void AfterSaveFailed(ITriggerContext context, Exception exception) { } + public virtual Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => Task.CompletedTask; + public virtual Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => Task.CompletedTask; + public virtual Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken) => Task.CompletedTask; } diff --git a/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs b/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs index 120c49e..d7961aa 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/TriggerContextExtensions.cs @@ -1,36 +1,35 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public static class TriggerContextExtensions { - public static class TriggerContextExtensions + /// + /// Get the DbContext EntityEntry for the Entity + /// + /// The EntityEntry associated with the DbContext + /// Throws when the context is not of type + public static EntityEntry GetEntry(this ITriggerContext context) + where TEntity : class { - /// - /// Get the DbContext EntityEntry for the Entity - /// - /// The EntityEntry associated with the DbContext - /// Throws when the context is not of type - public static EntityEntry GetEntry(this ITriggerContext context) - where TEntity : class - { - if (context is not TriggerContext typedContext) - throw new InvalidOperationException("GetEntry requires ITriggerContext to be of type TriggerContext"); + if (context is not TriggerContext typedContext) + throw new InvalidOperationException("GetEntry requires ITriggerContext to be of type TriggerContext"); - return typedContext.Entry; - } + return typedContext.Entry; + } - /// - /// Get the DbContext associated with this Entity - /// - /// The DbContext that fired this trigger - /// Throws when the context is not of type - public static DbContext GetDbContext(this ITriggerContext context) - where TEntity : class - { - if (context is not TriggerContext typedContext) - throw new InvalidOperationException("GetDbContext requires ITriggerContext to be of type TriggerContext"); + /// + /// Get the DbContext associated with this Entity + /// + /// The DbContext that fired this trigger + /// Throws when the context is not of type + public static DbContext GetDbContext(this ITriggerContext context) + where TEntity : class + { + if (context is not TriggerContext typedContext) + throw new InvalidOperationException("GetDbContext requires ITriggerContext to be of type TriggerContext"); - return typedContext.Entry.Context; - } + return typedContext.Entry.Context; } } diff --git a/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs b/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs index 797eefc..fc682d1 100644 --- a/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Extensions/TriggersContextOptionsBuilderExtensions.cs @@ -2,35 +2,34 @@ using EntityFrameworkCore.Triggered.Infrastructure; using Microsoft.Extensions.DependencyInjection; -namespace Microsoft.EntityFrameworkCore -{ - public static class TriggersContextOptionsBuilderExtensions - { - public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersContextOptionsBuilder builder) - => AddAssemblyTriggers(builder, Assembly.GetCallingAssembly()); +namespace Microsoft.EntityFrameworkCore; - public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersContextOptionsBuilder builder, ServiceLifetime lifetime) - => AddAssemblyTriggers(builder, lifetime, Assembly.GetCallingAssembly()); +public static class TriggersContextOptionsBuilderExtensions +{ + public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersContextOptionsBuilder builder) + => AddAssemblyTriggers(builder, Assembly.GetCallingAssembly()); - public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersContextOptionsBuilder builder, params Assembly[] assemblies) - => AddAssemblyTriggers(builder, ServiceLifetime.Scoped, assemblies); + public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersContextOptionsBuilder builder, ServiceLifetime lifetime) + => AddAssemblyTriggers(builder, lifetime, Assembly.GetCallingAssembly()); - public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersContextOptionsBuilder builder, ServiceLifetime lifetime, params Assembly[] assemblies) - { - ArgumentNullException.ThrowIfNull(assemblies); + public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersContextOptionsBuilder builder, params Assembly[] assemblies) + => AddAssemblyTriggers(builder, ServiceLifetime.Scoped, assemblies); - var assemblyTypes = assemblies - .SelectMany(x => x.GetTypes()) - .Where(x => x.IsClass) - .Where(x => !x.IsAbstract); + public static TriggersContextOptionsBuilder AddAssemblyTriggers(this TriggersContextOptionsBuilder builder, ServiceLifetime lifetime, params Assembly[] assemblies) + { + ArgumentNullException.ThrowIfNull(assemblies); - foreach (var assemblyType in assemblyTypes) - { - builder.AddTrigger(assemblyType, lifetime); - } + var assemblyTypes = assemblies + .SelectMany(x => x.GetTypes()) + .Where(x => x.IsClass) + .Where(x => !x.IsAbstract); - return builder; + foreach (var assemblyType in assemblyTypes) + { + builder.AddTrigger(assemblyType, lifetime); } + return builder; } + } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitAsyncTrigger.cs index 75ab51b..b85471a 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitAsyncTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions; + +public interface IAfterCommitAsyncTrigger + where TEntity : class { - public interface IAfterCommitAsyncTrigger - where TEntity : class - { - Task AfterCommitAsync(ITriggerContext context, CancellationToken cancellationToken); - } + Task AfterCommitAsync(ITriggerContext context, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitTrigger.cs index a81d65e..56115f8 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterCommitTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions; + +public interface IAfterCommitTrigger + where TEntity : class { - public interface IAfterCommitTrigger - where TEntity : class - { - void AfterCommit(ITriggerContext context); - } + void AfterCommit(ITriggerContext context); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackAsyncTrigger.cs index 5f2270d..ba6be07 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackAsyncTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions; + +public interface IAfterRollbackAsyncTrigger + where TEntity : class { - public interface IAfterRollbackAsyncTrigger - where TEntity : class - { - Task AfterRollbackAsync(ITriggerContext context, CancellationToken cancellationToken); - } + Task AfterRollbackAsync(ITriggerContext context, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackTrigger.cs index 550347d..1f9f297 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IAfterRollbackTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions; + +public interface IAfterRollbackTrigger + where TEntity : class { - public interface IAfterRollbackTrigger - where TEntity : class - { - void AfterRollback(ITriggerContext context); - } + void AfterRollback(ITriggerContext context); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitAsyncTrigger.cs index dfabed8..446d75a 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitAsyncTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions; + +public interface IBeforeCommitAsyncTrigger + where TEntity : class { - public interface IBeforeCommitAsyncTrigger - where TEntity : class - { - Task BeforeCommitAsync(ITriggerContext context, CancellationToken cancellationToken); - } + Task BeforeCommitAsync(ITriggerContext context, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitTrigger.cs index 39c3d02..f5a096b 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeCommitTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions; + +public interface IBeforeCommitTrigger + where TEntity : class { - public interface IBeforeCommitTrigger - where TEntity : class - { - void BeforeCommit(ITriggerContext context); - } + void BeforeCommit(ITriggerContext context); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackAsyncTrigger.cs index f9d640c..fdb70f4 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackAsyncTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions; + +public interface IBeforeRollbackAsyncTrigger + where TEntity : class { - public interface IBeforeRollbackAsyncTrigger - where TEntity : class - { - Task BeforeRollbackAsync(ITriggerContext context, CancellationToken cancellationToken); - } + Task BeforeRollbackAsync(ITriggerContext context, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackTrigger.cs index 1c6c368..6d8b2cd 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/IBeforeRollbackTrigger.cs @@ -1,8 +1,7 @@ -namespace EntityFrameworkCore.Triggered.Transactions +namespace EntityFrameworkCore.Triggered.Transactions; + +public interface IBeforeRollbackTrigger + where TEntity : class { - public interface IBeforeRollbackTrigger - where TEntity : class - { - void BeforeRollback(ITriggerContext context); - } + void BeforeRollback(ITriggerContext context); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedAsyncTrigger.cs index eb16816..0d0fc34 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles; + +public interface IAfterCommitCompletedAsyncTrigger { - public interface IAfterCommitCompletedAsyncTrigger - { - Task AfterCommitCompletedAsync(CancellationToken cancellationToken); - } + Task AfterCommitCompletedAsync(CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedTrigger.cs index c984fb4..1671e73 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitCompletedTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles; + +public interface IAfterCommitCompletedTrigger { - public interface IAfterCommitCompletedTrigger - { - void AfterCommitCompleted(); - } + void AfterCommitCompleted(); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingAsyncTrigger.cs index 1402269..b871665 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles; + +public interface IAfterCommitStartingAsyncTrigger { - public interface IAfterCommitStartingAsyncTrigger - { - Task AfterCommitStartingAsync(CancellationToken cancellationToken); - } + Task AfterCommitStartingAsync(CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingTrigger.cs index 706cd2c..c5b5d79 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IAfterCommitStartingTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles; + +public interface IAfterCommitStartingTrigger { - public interface IAfterCommitStartingTrigger - { - void AfterCommitStarting(); - } + void AfterCommitStarting(); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedAsyncTrigger.cs index b43fb8f..4ec58f7 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles; + +public interface IBeforeCommitCompletedAsyncTrigger { - public interface IBeforeCommitCompletedAsyncTrigger - { - Task BeforeCommitCompletedAsync(CancellationToken cancellationToken); - } + Task BeforeCommitCompletedAsync(CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedTrigger.cs index 07f9ec2..55b6394 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitCompletedTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles; + +public interface IBeforeCommitCompletedTrigger { - public interface IBeforeCommitCompletedTrigger - { - void BeforeCommitCompleted(); - } + void BeforeCommitCompleted(); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingAsyncTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingAsyncTrigger.cs index 59ea5d9..dcf7222 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingAsyncTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingAsyncTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles; + +public interface IBeforeCommitStartingAsyncTrigger { - public interface IBeforeCommitStartingAsyncTrigger - { - Task BeforeCommitStartingAsync(CancellationToken cancellationToken); - } + Task BeforeCommitStartingAsync(CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingTrigger.cs b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingTrigger.cs index bb82bfe..44e133a 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingTrigger.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions.Abstractions/Lifecycles/IBeforeCommitStartingTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles +namespace EntityFrameworkCore.Triggered.Transactions.Lifecycles; + +public interface IBeforeCommitStartingTrigger { - public interface IBeforeCommitStartingTrigger - { - void BeforeCommitStarting(); - } + void BeforeCommitStarting(); } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs b/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs index c1c387c..20716dc 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Extensions/TriggersContextOptionsBuilderExtensions.cs @@ -2,31 +2,30 @@ using EntityFrameworkCore.Triggered.Transactions; using EntityFrameworkCore.Triggered.Transactions.Lifecycles; -namespace Microsoft.EntityFrameworkCore +namespace Microsoft.EntityFrameworkCore; + +public static class TriggersContextOptionsBuilderExtensions { - public static class TriggersContextOptionsBuilderExtensions + public static TriggersContextOptionsBuilder UseTransactionTriggers(this TriggersContextOptionsBuilder triggersContextOptionsBuilder) { - public static TriggersContextOptionsBuilder UseTransactionTriggers(this TriggersContextOptionsBuilder triggersContextOptionsBuilder) - { - ArgumentNullException.ThrowIfNull(triggersContextOptionsBuilder); + ArgumentNullException.ThrowIfNull(triggersContextOptionsBuilder); - return triggersContextOptionsBuilder - .AddTriggerType(typeof(IBeforeCommitTrigger<>)) - .AddTriggerType(typeof(IBeforeCommitAsyncTrigger<>)) - .AddTriggerType(typeof(IAfterCommitTrigger<>)) - .AddTriggerType(typeof(IAfterCommitAsyncTrigger<>)) - .AddTriggerType(typeof(IBeforeRollbackTrigger<>)) - .AddTriggerType(typeof(IBeforeRollbackAsyncTrigger<>)) - .AddTriggerType(typeof(IAfterRollbackTrigger<>)) - .AddTriggerType(typeof(IAfterRollbackAsyncTrigger<>)) - .AddTriggerType(typeof(IBeforeCommitStartingTrigger)) - .AddTriggerType(typeof(IBeforeCommitStartingAsyncTrigger)) - .AddTriggerType(typeof(IBeforeCommitCompletedTrigger)) - .AddTriggerType(typeof(IBeforeCommitCompletedAsyncTrigger)) - .AddTriggerType(typeof(IAfterCommitStartingTrigger)) - .AddTriggerType(typeof(IAfterCommitStartingAsyncTrigger)) - .AddTriggerType(typeof(IAfterCommitCompletedTrigger)) - .AddTriggerType(typeof(IAfterCommitCompletedAsyncTrigger)); - } + return triggersContextOptionsBuilder + .AddTriggerType(typeof(IBeforeCommitTrigger<>)) + .AddTriggerType(typeof(IBeforeCommitAsyncTrigger<>)) + .AddTriggerType(typeof(IAfterCommitTrigger<>)) + .AddTriggerType(typeof(IAfterCommitAsyncTrigger<>)) + .AddTriggerType(typeof(IBeforeRollbackTrigger<>)) + .AddTriggerType(typeof(IBeforeRollbackAsyncTrigger<>)) + .AddTriggerType(typeof(IAfterRollbackTrigger<>)) + .AddTriggerType(typeof(IAfterRollbackAsyncTrigger<>)) + .AddTriggerType(typeof(IBeforeCommitStartingTrigger)) + .AddTriggerType(typeof(IBeforeCommitStartingAsyncTrigger)) + .AddTriggerType(typeof(IBeforeCommitCompletedTrigger)) + .AddTriggerType(typeof(IBeforeCommitCompletedAsyncTrigger)) + .AddTriggerType(typeof(IAfterCommitStartingTrigger)) + .AddTriggerType(typeof(IAfterCommitStartingAsyncTrigger)) + .AddTriggerType(typeof(IAfterCommitCompletedTrigger)) + .AddTriggerType(typeof(IAfterCommitCompletedAsyncTrigger)); } } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitAsyncTriggerDescriptor.cs index 37b3fae..fb013f8 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitAsyncTriggerDescriptor.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Transactions.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Internal; + +public class AfterCommitAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor { - public class AfterCommitAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor - { - readonly Func _invocationDelegate; - readonly Type _triggerType; + readonly Func _invocationDelegate; + readonly Type _triggerType; - public AfterCommitAsyncTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IAfterCommitAsyncTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IAfterCommitAsyncTrigger.AfterCommitAsync)); + public AfterCommitAsyncTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IAfterCommitAsyncTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IAfterCommitAsyncTrigger.AfterCommitAsync)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) - { - Debug.Assert(exception == null); + public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) + { + Debug.Assert(exception == null); - return _invocationDelegate(trigger, triggerContext, cancellationToken); - } + return _invocationDelegate(trigger, triggerContext, cancellationToken); } } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs index e073158..681c40a 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterCommitTriggerDescriptor.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Transactions.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Internal; + +public class AfterCommitTriggerDescriptor : ITriggerTypeDescriptor { - public class AfterCommitTriggerDescriptor : ITriggerTypeDescriptor - { - readonly Action _invocationDelegate; - readonly Type _triggerType; + readonly Action _invocationDelegate; + readonly Type _triggerType; - public AfterCommitTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IAfterCommitTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IAfterCommitTrigger.AfterCommit)); + public AfterCommitTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IAfterCommitTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IAfterCommitTrigger.AfterCommit)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public void Invoke(object trigger, object triggerContext, Exception? exception) - { - Debug.Assert(exception == null); + public void Invoke(object trigger, object triggerContext, Exception? exception) + { + Debug.Assert(exception == null); - _invocationDelegate(trigger, triggerContext); - } + _invocationDelegate(trigger, triggerContext); } } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackAsyncTriggerDescriptor.cs index 5c1d7e1..f439851 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackAsyncTriggerDescriptor.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Transactions.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Internal; + +public class AfterRollbackAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor { - public class AfterRollbackAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor - { - readonly Func _invocationDelegate; - readonly Type _triggerType; + readonly Func _invocationDelegate; + readonly Type _triggerType; - public AfterRollbackAsyncTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IAfterRollbackAsyncTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IAfterRollbackAsyncTrigger.AfterRollbackAsync)); + public AfterRollbackAsyncTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IAfterRollbackAsyncTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IAfterRollbackAsyncTrigger.AfterRollbackAsync)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) - { - Debug.Assert(exception == null); + public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) + { + Debug.Assert(exception == null); - return _invocationDelegate(trigger, triggerContext, cancellationToken); - } + return _invocationDelegate(trigger, triggerContext, cancellationToken); } } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs index 5fa5730..ac5c6a3 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/AfterRollbackTriggerDescriptor.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Transactions.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Internal; + +public class AfterRollbackTriggerDescriptor : ITriggerTypeDescriptor { - public class AfterRollbackTriggerDescriptor : ITriggerTypeDescriptor - { - readonly Action _invocationDelegate; - readonly Type _triggerType; + readonly Action _invocationDelegate; + readonly Type _triggerType; - public AfterRollbackTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IAfterRollbackTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IAfterRollbackTrigger.AfterRollback)); + public AfterRollbackTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IAfterRollbackTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IAfterRollbackTrigger.AfterRollback)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public void Invoke(object trigger, object triggerContext, Exception? exception) - { - Debug.Assert(exception == null); + public void Invoke(object trigger, object triggerContext, Exception? exception) + { + Debug.Assert(exception == null); - _invocationDelegate(trigger, triggerContext); - } + _invocationDelegate(trigger, triggerContext); } } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitAsyncTriggerDescriptor.cs index caf65e9..1b14deb 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitAsyncTriggerDescriptor.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Transactions.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Internal; + +public class BeforeCommitAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor { - public class BeforeCommitAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor - { - readonly Func _invocationDelegate; - readonly Type _triggerType; + readonly Func _invocationDelegate; + readonly Type _triggerType; - public BeforeCommitAsyncTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IBeforeCommitAsyncTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IBeforeCommitAsyncTrigger.BeforeCommitAsync)); + public BeforeCommitAsyncTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IBeforeCommitAsyncTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IBeforeCommitAsyncTrigger.BeforeCommitAsync)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) - { - Debug.Assert(exception == null); + public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) + { + Debug.Assert(exception == null); - return _invocationDelegate(trigger, triggerContext, cancellationToken); - } + return _invocationDelegate(trigger, triggerContext, cancellationToken); } } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs index 07cb5d3..09652ab 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeCommitTriggerDescriptor.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Transactions.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Internal; + +public class BeforeCommitTriggerDescriptor : ITriggerTypeDescriptor { - public class BeforeCommitTriggerDescriptor : ITriggerTypeDescriptor - { - readonly Action _invocationDelegate; - readonly Type _triggerType; + readonly Action _invocationDelegate; + readonly Type _triggerType; - public BeforeCommitTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IBeforeCommitTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IBeforeCommitTrigger.BeforeCommit)); + public BeforeCommitTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IBeforeCommitTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IBeforeCommitTrigger.BeforeCommit)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public void Invoke(object trigger, object triggerContext, Exception? exception) - { - Debug.Assert(exception == null); + public void Invoke(object trigger, object triggerContext, Exception? exception) + { + Debug.Assert(exception == null); - _invocationDelegate(trigger, triggerContext); - } + _invocationDelegate(trigger, triggerContext); } } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackAsyncTriggerDescriptor.cs index a33f88a..0151479 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackAsyncTriggerDescriptor.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Transactions.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Internal; + +public class BeforeRollbackAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor { - public class BeforeRollbackAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor - { - readonly Func _invocationDelegate; - readonly Type _triggerType; + readonly Func _invocationDelegate; + readonly Type _triggerType; - public BeforeRollbackAsyncTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IBeforeRollbackAsyncTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IBeforeRollbackAsyncTrigger.BeforeRollbackAsync)); + public BeforeRollbackAsyncTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IBeforeRollbackAsyncTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IBeforeRollbackAsyncTrigger.BeforeRollbackAsync)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) - { - Debug.Assert(exception == null); + public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) + { + Debug.Assert(exception == null); - return _invocationDelegate(trigger, triggerContext, cancellationToken); - } + return _invocationDelegate(trigger, triggerContext, cancellationToken); } } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs index eee0dab..4e1b87f 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/Internal/BeforeRollbackTriggerDescriptor.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Internal; using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Transactions.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Internal; + +public class BeforeRollbackTriggerDescriptor : ITriggerTypeDescriptor { - public class BeforeRollbackTriggerDescriptor : ITriggerTypeDescriptor - { - readonly Action _invocationDelegate; - readonly Type _triggerType; + readonly Action _invocationDelegate; + readonly Type _triggerType; - public BeforeRollbackTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IBeforeRollbackTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IBeforeRollbackTrigger.BeforeRollback)); + public BeforeRollbackTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IBeforeRollbackTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IBeforeRollbackTrigger.BeforeRollback)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public void Invoke(object trigger, object triggerContext, Exception? exception) - { - Debug.Assert(exception == null); + public void Invoke(object trigger, object triggerContext, Exception? exception) + { + Debug.Assert(exception == null); - _invocationDelegate(trigger, triggerContext); - } + _invocationDelegate(trigger, triggerContext); } } diff --git a/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs b/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs index def5702..617b949 100644 --- a/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs +++ b/src/EntityFrameworkCore.Triggered.Transactions/TriggeredSessionExtensions.cs @@ -3,223 +3,222 @@ using EntityFrameworkCore.Triggered.Transactions.Internal; using EntityFrameworkCore.Triggered.Transactions.Lifecycles; -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public static class TriggeredSessionExtensions { - public static class TriggeredSessionExtensions + static ITriggerContextDiscoveryStrategy? _beforeCommitTriggerContextDiscoveryStrategy; + static ITriggerContextDiscoveryStrategy? _afterCommitTriggerContextDiscoveryStrategy; + + static ITriggerContextDiscoveryStrategy? _beforeRollbackTriggerContextDiscoveryStrategy; + static ITriggerContextDiscoveryStrategy? _afterRollbackTriggerContextDiscoveryStrategy; + + public static void RaiseBeforeCommitTriggers(this ITriggerSession triggerSession) { - static ITriggerContextDiscoveryStrategy? _beforeCommitTriggerContextDiscoveryStrategy; - static ITriggerContextDiscoveryStrategy? _afterCommitTriggerContextDiscoveryStrategy; + ArgumentNullException.ThrowIfNull(triggerSession); - static ITriggerContextDiscoveryStrategy? _beforeRollbackTriggerContextDiscoveryStrategy; - static ITriggerContextDiscoveryStrategy? _afterRollbackTriggerContextDiscoveryStrategy; + _beforeCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeCommit"); - public static void RaiseBeforeCommitTriggers(this ITriggerSession triggerSession) - { - ArgumentNullException.ThrowIfNull(triggerSession); + ((TriggerSession)triggerSession).RaiseTriggers(typeof(IBeforeCommitTrigger<>), null, _beforeCommitTriggerContextDiscoveryStrategy, entityType => new BeforeCommitTriggerDescriptor(entityType)); + } - _beforeCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeCommit"); + public static Task RaiseBeforeCommitAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(triggerSession); - ((TriggerSession)triggerSession).RaiseTriggers(typeof(IBeforeCommitTrigger<>), null, _beforeCommitTriggerContextDiscoveryStrategy, entityType => new BeforeCommitTriggerDescriptor(entityType)); - } + _beforeCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeCommit"); - public static Task RaiseBeforeCommitAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(triggerSession); + return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IBeforeCommitAsyncTrigger<>), null, _beforeCommitTriggerContextDiscoveryStrategy, entityType => new BeforeCommitAsyncTriggerDescriptor(entityType), cancellationToken); + } - _beforeCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeCommit"); + public static void RaiseAfterCommitTriggers(this ITriggerSession triggerSession) + { + ArgumentNullException.ThrowIfNull(triggerSession); - return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IBeforeCommitAsyncTrigger<>), null, _beforeCommitTriggerContextDiscoveryStrategy, entityType => new BeforeCommitAsyncTriggerDescriptor(entityType), cancellationToken); - } + _afterCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterCommit"); - public static void RaiseAfterCommitTriggers(this ITriggerSession triggerSession) - { - ArgumentNullException.ThrowIfNull(triggerSession); + ((TriggerSession)triggerSession).RaiseTriggers(typeof(IAfterCommitTrigger<>), null, _afterCommitTriggerContextDiscoveryStrategy, entityType => new AfterCommitTriggerDescriptor(entityType)); + } - _afterCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterCommit"); + public static Task RaiseAfterCommitAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(triggerSession); - ((TriggerSession)triggerSession).RaiseTriggers(typeof(IAfterCommitTrigger<>), null, _afterCommitTriggerContextDiscoveryStrategy, entityType => new AfterCommitTriggerDescriptor(entityType)); - } + _afterCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterCommit"); - public static Task RaiseAfterCommitAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(triggerSession); + return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IAfterCommitAsyncTrigger<>), null, _afterCommitTriggerContextDiscoveryStrategy, entityType => new AfterCommitAsyncTriggerDescriptor(entityType), cancellationToken); + } - _afterCommitTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterCommit"); + public static void RaiseBeforeRollbackTriggers(this ITriggerSession triggerSession) + { + ArgumentNullException.ThrowIfNull(triggerSession); - return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IAfterCommitAsyncTrigger<>), null, _afterCommitTriggerContextDiscoveryStrategy, entityType => new AfterCommitAsyncTriggerDescriptor(entityType), cancellationToken); - } + _beforeRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeRollback"); - public static void RaiseBeforeRollbackTriggers(this ITriggerSession triggerSession) - { - ArgumentNullException.ThrowIfNull(triggerSession); + ((TriggerSession)triggerSession).RaiseTriggers(typeof(IBeforeRollbackTrigger<>), null, _beforeRollbackTriggerContextDiscoveryStrategy, entityType => new BeforeRollbackTriggerDescriptor(entityType)); + } - _beforeRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeRollback"); + public static Task RaiseBeforeRollbackAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(triggerSession); - ((TriggerSession)triggerSession).RaiseTriggers(typeof(IBeforeRollbackTrigger<>), null, _beforeRollbackTriggerContextDiscoveryStrategy, entityType => new BeforeRollbackTriggerDescriptor(entityType)); - } + _beforeRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeRollback"); - public static Task RaiseBeforeRollbackAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(triggerSession); + return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IBeforeRollbackAsyncTrigger<>), null, _beforeRollbackTriggerContextDiscoveryStrategy, entityType => new BeforeRollbackAsyncTriggerDescriptor(entityType), cancellationToken); + } - _beforeRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("BeforeRollback"); + public static void RaiseAfterRollbackTriggers(this ITriggerSession triggerSession) + { + ArgumentNullException.ThrowIfNull(triggerSession); - return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IBeforeRollbackAsyncTrigger<>), null, _beforeRollbackTriggerContextDiscoveryStrategy, entityType => new BeforeRollbackAsyncTriggerDescriptor(entityType), cancellationToken); - } + _afterRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterRollback"); - public static void RaiseAfterRollbackTriggers(this ITriggerSession triggerSession) - { - ArgumentNullException.ThrowIfNull(triggerSession); + ((TriggerSession)triggerSession).RaiseTriggers(typeof(IAfterRollbackTrigger<>), null, _afterRollbackTriggerContextDiscoveryStrategy, entityType => new AfterRollbackTriggerDescriptor(entityType)); + } - _afterRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterRollback"); + public static Task RaiseAfterRollbackAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(triggerSession); - ((TriggerSession)triggerSession).RaiseTriggers(typeof(IAfterRollbackTrigger<>), null, _afterRollbackTriggerContextDiscoveryStrategy, entityType => new AfterRollbackTriggerDescriptor(entityType)); - } + _afterRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterRollback"); - public static Task RaiseAfterRollbackAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(triggerSession); + return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IAfterRollbackAsyncTrigger<>), null, _afterRollbackTriggerContextDiscoveryStrategy, entityType => new AfterRollbackAsyncTriggerDescriptor(entityType), cancellationToken); + } - _afterRollbackTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterRollback"); + public static void RaiseBeforeCommitStartingTriggers(this ITriggerSession triggerSession) + { + ArgumentNullException.ThrowIfNull(triggerSession); - return ((TriggerSession)triggerSession).RaiseAsyncTriggers(typeof(IAfterRollbackAsyncTrigger<>), null, _afterRollbackTriggerContextDiscoveryStrategy, entityType => new AfterRollbackAsyncTriggerDescriptor(entityType), cancellationToken); + if (triggerSession is not TriggerSession typedTriggerSession) + { + throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); } - public static void RaiseBeforeCommitStartingTriggers(this ITriggerSession triggerSession) + var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); + + foreach (var trigger in triggers) { - ArgumentNullException.ThrowIfNull(triggerSession); + trigger.BeforeCommitStarting(); + } + } - if (triggerSession is not TriggerSession typedTriggerSession) - { - throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); - } - var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); + public async static Task RaiseBeforeCommitStartingAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(triggerSession); - foreach (var trigger in triggers) - { - trigger.BeforeCommitStarting(); - } + if (triggerSession is not TriggerSession typedTriggerSession) + { + throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); } + var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); - public async static Task RaiseBeforeCommitStartingAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + foreach (var trigger in triggers) { - ArgumentNullException.ThrowIfNull(triggerSession); - - if (triggerSession is not TriggerSession typedTriggerSession) - { - throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); - } - - var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); - - foreach (var trigger in triggers) - { - await trigger.BeforeCommitStartingAsync(cancellationToken); - } + await trigger.BeforeCommitStartingAsync(cancellationToken); } + } - public static void RaiseBeforeCommitCompletedTriggers(this ITriggerSession triggerSession) - { - ArgumentNullException.ThrowIfNull(triggerSession); + public static void RaiseBeforeCommitCompletedTriggers(this ITriggerSession triggerSession) + { + ArgumentNullException.ThrowIfNull(triggerSession); - if (triggerSession is not TriggerSession typedTriggerSession) - { - throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); - } + if (triggerSession is not TriggerSession typedTriggerSession) + { + throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); + } - var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); + var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - trigger.BeforeCommitCompleted(); - } + foreach (var trigger in triggers) + { + trigger.BeforeCommitCompleted(); } + } - public async static Task RaiseBeforeCommitCompletedAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(triggerSession); + public async static Task RaiseBeforeCommitCompletedAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(triggerSession); - if (triggerSession is not TriggerSession typedTriggerSession) - { - throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); - } + if (triggerSession is not TriggerSession typedTriggerSession) + { + throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); + } - var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); + var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - await trigger.BeforeCommitCompletedAsync(cancellationToken); - } + foreach (var trigger in triggers) + { + await trigger.BeforeCommitCompletedAsync(cancellationToken); } + } - public static void RaiseAfterCommitStartingTriggers(this ITriggerSession triggerSession) - { - ArgumentNullException.ThrowIfNull(triggerSession); + public static void RaiseAfterCommitStartingTriggers(this ITriggerSession triggerSession) + { + ArgumentNullException.ThrowIfNull(triggerSession); - if (triggerSession is not TriggerSession typedTriggerSession) - { - throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); - } + if (triggerSession is not TriggerSession typedTriggerSession) + { + throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); + } - var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); + var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - trigger.AfterCommitStarting(); - } + foreach (var trigger in triggers) + { + trigger.AfterCommitStarting(); } + } - public async static Task RaiseAfterCommitStartingAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(triggerSession); + public async static Task RaiseAfterCommitStartingAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(triggerSession); - if (triggerSession is not TriggerSession typedTriggerSession) - { - throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); - } + if (triggerSession is not TriggerSession typedTriggerSession) + { + throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); + } - var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); + var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - await trigger.AfterCommitStartingAsync(cancellationToken); - } + foreach (var trigger in triggers) + { + await trigger.AfterCommitStartingAsync(cancellationToken); } + } - public static void RaiseAfterCommitCompletedTriggers(this ITriggerSession triggerSession) - { - ArgumentNullException.ThrowIfNull(triggerSession); + public static void RaiseAfterCommitCompletedTriggers(this ITriggerSession triggerSession) + { + ArgumentNullException.ThrowIfNull(triggerSession); - if (triggerSession is not TriggerSession typedTriggerSession) - { - throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); - } + if (triggerSession is not TriggerSession typedTriggerSession) + { + throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); + } - var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); + var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - trigger.AfterCommitCompleted(); - } + foreach (var trigger in triggers) + { + trigger.AfterCommitCompleted(); } + } - public async static Task RaiseAfterCommitCompletedAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(triggerSession); + public async static Task RaiseAfterCommitCompletedAsyncTriggers(this ITriggerSession triggerSession, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(triggerSession); - if (triggerSession is not TriggerSession typedTriggerSession) - { - throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); - } + if (triggerSession is not TriggerSession typedTriggerSession) + { + throw new InvalidOperationException("Method is implemented for concrete TriggerSessions only"); + } - var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); + var triggers = typedTriggerSession.DiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - await trigger.AfterCommitCompletedAsync(cancellationToken); - } + foreach (var trigger in triggers) + { + await trigger.AfterCommitCompletedAsync(cancellationToken); } } } diff --git a/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs b/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs index 6345bb3..ff86ac8 100644 --- a/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs +++ b/src/EntityFrameworkCore.Triggered/Extensions/DbContextExtensions.cs @@ -1,86 +1,85 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -namespace EntityFrameworkCore.Triggered.Extensions +namespace EntityFrameworkCore.Triggered.Extensions; + +public static class DbContextExtensions { - public static class DbContextExtensions + /// + /// Gets the ITriggerService that is used to create trigger sessions.Allows for just in time configuration + /// + public static ITriggerService GetTriggerService(this DbContext dbContext) { - /// - /// Gets the ITriggerService that is used to create trigger sessions.Allows for just in time configuration - /// - public static ITriggerService GetTriggerService(this DbContext dbContext) - { - ArgumentNullException.ThrowIfNull(dbContext); + ArgumentNullException.ThrowIfNull(dbContext); - return dbContext.GetService() ?? throw new InvalidOperationException("Triggers are not configured for this DbContext"); - } + return dbContext.GetService() ?? throw new InvalidOperationException("Triggers are not configured for this DbContext"); + } - /// - /// Gets or creates a ITriggerSession that can be used to manually invoke triggers - /// - public static ITriggerSession CreateTriggerSession(this DbContext dbContext, IServiceProvider? serviceProvider = null) - { - var triggerService = GetTriggerService(dbContext); + /// + /// Gets or creates a ITriggerSession that can be used to manually invoke triggers + /// + public static ITriggerSession CreateTriggerSession(this DbContext dbContext, IServiceProvider? serviceProvider = null) + { + var triggerService = GetTriggerService(dbContext); - return triggerService.CreateSession(dbContext, serviceProvider); - } + return triggerService.CreateSession(dbContext, serviceProvider); + } - /// - /// Creates a ITriggerSession that can be used to manually invoke triggers - /// - public static ITriggerSession CreateTriggerSession(this DbContext dbContext, Func configurator, IServiceProvider? serviceProvider = null) - { - var triggerService = GetTriggerService(dbContext); - var configuration = configurator(triggerService.Configuration); + /// + /// Creates a ITriggerSession that can be used to manually invoke triggers + /// + public static ITriggerSession CreateTriggerSession(this DbContext dbContext, Func configurator, IServiceProvider? serviceProvider = null) + { + var triggerService = GetTriggerService(dbContext); + var configuration = configurator(triggerService.Configuration); - return triggerService.CreateSession(dbContext, configuration, serviceProvider); - } + return triggerService.CreateSession(dbContext, configuration, serviceProvider); + } - /// - /// Creates a new ITriggerSession that can be used to manually invoke triggers. Throws if a TriggerSession is already active - /// - public static ITriggerSession CreateNewTriggerSession(this DbContext dbContext, Func? configurator = null, IServiceProvider? serviceProvider = null) + /// + /// Creates a new ITriggerSession that can be used to manually invoke triggers. Throws if a TriggerSession is already active + /// + public static ITriggerSession CreateNewTriggerSession(this DbContext dbContext, Func? configurator = null, IServiceProvider? serviceProvider = null) + { + var triggerService = GetTriggerService(dbContext); + if (triggerService.Current is not null) { - var triggerService = GetTriggerService(dbContext); - if (triggerService.Current is not null) - { - throw new InvalidOperationException("A triggerSession has already been created"); - } + throw new InvalidOperationException("A triggerSession has already been created"); + } - var configuration = configurator?.Invoke(triggerService.Configuration) ?? triggerService.Configuration; + var configuration = configurator?.Invoke(triggerService.Configuration) ?? triggerService.Configuration; - return triggerService.CreateSession(dbContext, configuration, serviceProvider); - } + return triggerService.CreateSession(dbContext, configuration, serviceProvider); + } - /// - /// Calls dbContext.SaveChanges without invoking triggers - /// - public static int SaveChangesWithoutTriggers(this DbContext dbContext, bool acceptAllChangesOnSuccess = true) - { - CreateNewTriggerSession(dbContext, configuration => configuration with { - Disabled = true - }); + /// + /// Calls dbContext.SaveChanges without invoking triggers + /// + public static int SaveChangesWithoutTriggers(this DbContext dbContext, bool acceptAllChangesOnSuccess = true) + { + CreateNewTriggerSession(dbContext, configuration => configuration with { + Disabled = true + }); - return dbContext.SaveChanges(acceptAllChangesOnSuccess); - } + return dbContext.SaveChanges(acceptAllChangesOnSuccess); + } - /// - /// Calls dbContext.SaveChanges without invoking triggers - /// - public static Task SaveChangesWithoutTriggersAsync(this DbContext dbContext, CancellationToken cancellationToken = default) - => SaveChangesWithoutTriggersAsync(dbContext, true, cancellationToken); + /// + /// Calls dbContext.SaveChanges without invoking triggers + /// + public static Task SaveChangesWithoutTriggersAsync(this DbContext dbContext, CancellationToken cancellationToken = default) + => SaveChangesWithoutTriggersAsync(dbContext, true, cancellationToken); - /// - /// Calls dbContext.SaveChanges without invoking triggers - /// - public static Task SaveChangesWithoutTriggersAsync(this DbContext dbContext, bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) - { - CreateNewTriggerSession(dbContext, configuration => configuration with { - Disabled = true - }); + /// + /// Calls dbContext.SaveChanges without invoking triggers + /// + public static Task SaveChangesWithoutTriggersAsync(this DbContext dbContext, bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) + { + CreateNewTriggerSession(dbContext, configuration => configuration with { + Disabled = true + }); - return dbContext.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } + return dbContext.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); } } diff --git a/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs b/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs index 9e4faaa..8f42969 100644 --- a/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs +++ b/src/EntityFrameworkCore.Triggered/Extensions/ServiceCollectionExtensions.cs @@ -3,176 +3,175 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace Microsoft.Extensions.DependencyInjection +namespace Microsoft.Extensions.DependencyInjection; + +public static class ServiceCollectionExtensions { - public static class ServiceCollectionExtensions + private static object SetApplicationTriggerServiceProviderAccessor(object instance, IServiceProvider serviceProvider) { - private static object SetApplicationTriggerServiceProviderAccessor(object instance, IServiceProvider serviceProvider) + if (instance is DbContext dbContext) { - if (instance is DbContext dbContext) + var applicationTriggerServiceProviderAccessor = dbContext.GetService(); + if (applicationTriggerServiceProviderAccessor != null) { - var applicationTriggerServiceProviderAccessor = dbContext.GetService(); - if (applicationTriggerServiceProviderAccessor != null) - { - applicationTriggerServiceProviderAccessor.SetTriggerServiceProvider(serviceProvider); - } + applicationTriggerServiceProviderAccessor.SetTriggerServiceProvider(serviceProvider); } - - return instance; } - public static IServiceCollection AddTriggeredDbContext(this IServiceCollection serviceCollection, Action? optionsAction = null, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) - where TContext : DbContext - { - serviceCollection.AddDbContext(options => { - optionsAction?.Invoke(options); - options.UseTriggers(); - }, contextLifetime, optionsLifetime); + return instance; + } - return serviceCollection; - } + public static IServiceCollection AddTriggeredDbContext(this IServiceCollection serviceCollection, Action? optionsAction = null, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) + where TContext : DbContext + { + serviceCollection.AddDbContext(options => { + optionsAction?.Invoke(options); + options.UseTriggers(); + }, contextLifetime, optionsLifetime); - public static IServiceCollection AddTriggeredDbContextPool(this IServiceCollection serviceCollection, Action? optionsAction = null, int poolSize = 1024) - where TContext : DbContext - { - serviceCollection.AddDbContextPool(options => { - optionsAction?.Invoke(options); - options.UseTriggers(); - }, poolSize); + return serviceCollection; + } - var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(TContext)); - if (serviceDescriptor?.ImplementationFactory != null) - { - serviceCollection.Replace(ServiceDescriptor.Describe( - serviceType: typeof(TContext), - implementationFactory: serviceProvider => SetApplicationTriggerServiceProviderAccessor(serviceDescriptor.ImplementationFactory(serviceProvider), serviceProvider), - lifetime: ServiceLifetime.Transient - )); - } + public static IServiceCollection AddTriggeredDbContextPool(this IServiceCollection serviceCollection, Action? optionsAction = null, int poolSize = 1024) + where TContext : DbContext + { + serviceCollection.AddDbContextPool(options => { + optionsAction?.Invoke(options); + options.UseTriggers(); + }, poolSize); - return serviceCollection; + var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(TContext)); + if (serviceDescriptor?.ImplementationFactory != null) + { + serviceCollection.Replace(ServiceDescriptor.Describe( + serviceType: typeof(TContext), + implementationFactory: serviceProvider => SetApplicationTriggerServiceProviderAccessor(serviceDescriptor.ImplementationFactory(serviceProvider), serviceProvider), + lifetime: ServiceLifetime.Transient + )); } - public static IServiceCollection AddTriggeredDbContextPool(this IServiceCollection serviceCollection, Action? optionsAction = null, int poolSize = 1024) - where TContext : class where TImplementation : DbContext, TContext - { - serviceCollection.AddDbContextPool(options => { - optionsAction?.Invoke(options); - options.UseTriggers(); - }, poolSize); + return serviceCollection; + } - var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(TContext)); - if (serviceDescriptor?.ImplementationFactory != null) - { - serviceCollection.Replace(ServiceDescriptor.Describe( - serviceType: typeof(TContext), - implementationFactory: serviceProvider => SetApplicationTriggerServiceProviderAccessor(serviceDescriptor.ImplementationFactory(serviceProvider), serviceProvider), - lifetime: ServiceLifetime.Transient - )); - } + public static IServiceCollection AddTriggeredDbContextPool(this IServiceCollection serviceCollection, Action? optionsAction = null, int poolSize = 1024) + where TContext : class where TImplementation : DbContext, TContext + { + serviceCollection.AddDbContextPool(options => { + optionsAction?.Invoke(options); + options.UseTriggers(); + }, poolSize); - return serviceCollection; + var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(TContext)); + if (serviceDescriptor?.ImplementationFactory != null) + { + serviceCollection.Replace(ServiceDescriptor.Describe( + serviceType: typeof(TContext), + implementationFactory: serviceProvider => SetApplicationTriggerServiceProviderAccessor(serviceDescriptor.ImplementationFactory(serviceProvider), serviceProvider), + lifetime: ServiceLifetime.Transient + )); } - public static IServiceCollection AddTriggeredDbContextFactory(this IServiceCollection serviceCollection, Action? optionsAction = null, ServiceLifetime lifetime = ServiceLifetime.Singleton) - where TContext : DbContext - { - serviceCollection.AddDbContextFactory(options => { - optionsAction?.Invoke(options); - options.UseTriggers(); - }, lifetime); + return serviceCollection; + } - var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(IDbContextFactory)); + public static IServiceCollection AddTriggeredDbContextFactory(this IServiceCollection serviceCollection, Action? optionsAction = null, ServiceLifetime lifetime = ServiceLifetime.Singleton) + where TContext : DbContext + { + serviceCollection.AddDbContextFactory(options => { + optionsAction?.Invoke(options); + options.UseTriggers(); + }, lifetime); - if (serviceDescriptor?.ImplementationType != null) - { - var triggeredFactoryType = typeof(TriggeredDbContextFactory<,>).MakeGenericType(typeof(TContext), serviceDescriptor.ImplementationType); - - serviceCollection.TryAdd(ServiceDescriptor.Describe( - serviceType: serviceDescriptor.ImplementationType, - implementationType: serviceDescriptor.ImplementationType, - lifetime: serviceDescriptor.Lifetime - )); - - serviceCollection.Replace(ServiceDescriptor.Describe( - serviceType: typeof(IDbContextFactory), - implementationFactory: serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, triggeredFactoryType, serviceProvider.GetRequiredService(serviceDescriptor.ImplementationType), serviceProvider), - lifetime: ServiceLifetime.Transient - )); - } + var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(IDbContextFactory)); - return serviceCollection; + if (serviceDescriptor?.ImplementationType != null) + { + var triggeredFactoryType = typeof(TriggeredDbContextFactory<,>).MakeGenericType(typeof(TContext), serviceDescriptor.ImplementationType); + + serviceCollection.TryAdd(ServiceDescriptor.Describe( + serviceType: serviceDescriptor.ImplementationType, + implementationType: serviceDescriptor.ImplementationType, + lifetime: serviceDescriptor.Lifetime + )); + + serviceCollection.Replace(ServiceDescriptor.Describe( + serviceType: typeof(IDbContextFactory), + implementationFactory: serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, triggeredFactoryType, serviceProvider.GetRequiredService(serviceDescriptor.ImplementationType), serviceProvider), + lifetime: ServiceLifetime.Transient + )); } - public static IServiceCollection AddTriggeredDbContextFactory(this IServiceCollection serviceCollection, Action? optionsAction = null, ServiceLifetime lifetime = ServiceLifetime.Singleton) - where TContext : DbContext - where TFactory : IDbContextFactory - { - serviceCollection.AddDbContextFactory(options => { - optionsAction?.Invoke(options); - options.UseTriggers(); - }, lifetime); + return serviceCollection; + } - var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(IDbContextFactory)); + public static IServiceCollection AddTriggeredDbContextFactory(this IServiceCollection serviceCollection, Action? optionsAction = null, ServiceLifetime lifetime = ServiceLifetime.Singleton) + where TContext : DbContext + where TFactory : IDbContextFactory + { + serviceCollection.AddDbContextFactory(options => { + optionsAction?.Invoke(options); + options.UseTriggers(); + }, lifetime); - if (serviceDescriptor?.ImplementationType != null) - { - var triggeredFactoryType = typeof(TriggeredDbContextFactory<,>).MakeGenericType(typeof(TContext), serviceDescriptor.ImplementationType); - - serviceCollection.TryAdd(ServiceDescriptor.Describe( - serviceType: serviceDescriptor.ImplementationType, - implementationType: serviceDescriptor.ImplementationType, - lifetime: serviceDescriptor.Lifetime - )); - - serviceCollection.Replace(ServiceDescriptor.Describe( - serviceType: typeof(IDbContextFactory), - implementationFactory: serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, triggeredFactoryType, serviceProvider.GetRequiredService(serviceDescriptor.ImplementationType), serviceProvider), - lifetime: ServiceLifetime.Transient - )); - } + var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(IDbContextFactory)); - return serviceCollection; + if (serviceDescriptor?.ImplementationType != null) + { + var triggeredFactoryType = typeof(TriggeredDbContextFactory<,>).MakeGenericType(typeof(TContext), serviceDescriptor.ImplementationType); + + serviceCollection.TryAdd(ServiceDescriptor.Describe( + serviceType: serviceDescriptor.ImplementationType, + implementationType: serviceDescriptor.ImplementationType, + lifetime: serviceDescriptor.Lifetime + )); + + serviceCollection.Replace(ServiceDescriptor.Describe( + serviceType: typeof(IDbContextFactory), + implementationFactory: serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, triggeredFactoryType, serviceProvider.GetRequiredService(serviceDescriptor.ImplementationType), serviceProvider), + lifetime: ServiceLifetime.Transient + )); } - public static IServiceCollection AddTriggeredPooledDbContextFactory(this IServiceCollection serviceCollection, Action? optionsAction = null, int poolSize = 128) - where TContext : DbContext - { - serviceCollection.AddPooledDbContextFactory(options => { - optionsAction?.Invoke(options); - options.UseTriggers(); - }, poolSize); + return serviceCollection; + } - var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(IDbContextFactory)); + public static IServiceCollection AddTriggeredPooledDbContextFactory(this IServiceCollection serviceCollection, Action? optionsAction = null, int poolSize = 128) + where TContext : DbContext + { + serviceCollection.AddPooledDbContextFactory(options => { + optionsAction?.Invoke(options); + options.UseTriggers(); + }, poolSize); - if (serviceDescriptor?.ImplementationType != null) - { - var triggeredFactoryType = typeof(TriggeredDbContextFactory<,>).MakeGenericType(typeof(TContext), serviceDescriptor.ImplementationType); - - serviceCollection.TryAdd(ServiceDescriptor.Describe( - serviceType: serviceDescriptor.ImplementationType, - implementationType: serviceDescriptor.ImplementationType, - lifetime: serviceDescriptor.Lifetime - )); - - serviceCollection.Replace(ServiceDescriptor.Describe( - serviceType: typeof(IDbContextFactory), - implementationFactory: serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, triggeredFactoryType, serviceProvider.GetRequiredService(serviceDescriptor.ImplementationType), serviceProvider), - lifetime: ServiceLifetime.Scoped - )); - } + var serviceDescriptor = serviceCollection.FirstOrDefault(x => x.ServiceType == typeof(IDbContextFactory)); - if (serviceDescriptor?.ImplementationFactory != null) - { - var triggeredFactoryType = typeof(TriggeredDbContextFactory<>).MakeGenericType(typeof(TContext)); + if (serviceDescriptor?.ImplementationType != null) + { + var triggeredFactoryType = typeof(TriggeredDbContextFactory<,>).MakeGenericType(typeof(TContext), serviceDescriptor.ImplementationType); + + serviceCollection.TryAdd(ServiceDescriptor.Describe( + serviceType: serviceDescriptor.ImplementationType, + implementationType: serviceDescriptor.ImplementationType, + lifetime: serviceDescriptor.Lifetime + )); + + serviceCollection.Replace(ServiceDescriptor.Describe( + serviceType: typeof(IDbContextFactory), + implementationFactory: serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, triggeredFactoryType, serviceProvider.GetRequiredService(serviceDescriptor.ImplementationType), serviceProvider), + lifetime: ServiceLifetime.Scoped + )); + } - serviceCollection.Replace(ServiceDescriptor.Describe( - serviceType: typeof(IDbContextFactory), - implementationFactory: serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, triggeredFactoryType, serviceDescriptor.ImplementationFactory), - lifetime: ServiceLifetime.Scoped - )); - } - return serviceCollection; + if (serviceDescriptor?.ImplementationFactory != null) + { + var triggeredFactoryType = typeof(TriggeredDbContextFactory<>).MakeGenericType(typeof(TContext)); + + serviceCollection.Replace(ServiceDescriptor.Describe( + serviceType: typeof(IDbContextFactory), + implementationFactory: serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, triggeredFactoryType, serviceDescriptor.ImplementationFactory), + lifetime: ServiceLifetime.Scoped + )); } + return serviceCollection; } } diff --git a/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs b/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs index 4c58fc0..7e2bd9b 100644 --- a/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs +++ b/src/EntityFrameworkCore.Triggered/Extensions/TriggersDbContextOptionsExtensions.cs @@ -2,26 +2,25 @@ using EntityFrameworkCore.Triggered.Infrastructure.Internal; using Microsoft.EntityFrameworkCore.Infrastructure; -namespace Microsoft.EntityFrameworkCore +namespace Microsoft.EntityFrameworkCore; + +/// +/// Triggers-specific extension methods for . +/// +public static class TriggersDbContextOptionsExtensions { - /// - /// Triggers-specific extension methods for . - /// - public static class TriggersDbContextOptionsExtensions - { - public static DbContextOptionsBuilder UseTriggers(this DbContextOptionsBuilder optionsBuilder, Action? configure = null) - where TContext : DbContext => (DbContextOptionsBuilder)UseTriggers((DbContextOptionsBuilder)optionsBuilder, configure); + public static DbContextOptionsBuilder UseTriggers(this DbContextOptionsBuilder optionsBuilder, Action? configure = null) + where TContext : DbContext => (DbContextOptionsBuilder)UseTriggers((DbContextOptionsBuilder)optionsBuilder, configure); - public static DbContextOptionsBuilder UseTriggers(this DbContextOptionsBuilder optionsBuilder, Action? configure = null) - { - ArgumentNullException.ThrowIfNull(optionsBuilder); + public static DbContextOptionsBuilder UseTriggers(this DbContextOptionsBuilder optionsBuilder, Action? configure = null) + { + ArgumentNullException.ThrowIfNull(optionsBuilder); - var extension = optionsBuilder.Options.FindExtension() ?? new TriggersOptionExtension(); - ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + var extension = optionsBuilder.Options.FindExtension() ?? new TriggersOptionExtension(); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); - configure?.Invoke(new TriggersContextOptionsBuilder(optionsBuilder)); + configure?.Invoke(new TriggersContextOptionsBuilder(optionsBuilder)); - return optionsBuilder; - } + return optionsBuilder; } } diff --git a/src/EntityFrameworkCore.Triggered/ITriggerService.cs b/src/EntityFrameworkCore.Triggered/ITriggerService.cs index 1f5d1d6..26c318a 100644 --- a/src/EntityFrameworkCore.Triggered/ITriggerService.cs +++ b/src/EntityFrameworkCore.Triggered/ITriggerService.cs @@ -1,15 +1,14 @@ using Microsoft.EntityFrameworkCore; -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public interface ITriggerService { - public interface ITriggerService - { - TriggerSessionConfiguration Configuration { get; set; } + TriggerSessionConfiguration Configuration { get; set; } - ITriggerSession CreateSession(DbContext context, IServiceProvider? serviceProvider = null); + ITriggerSession CreateSession(DbContext context, IServiceProvider? serviceProvider = null); - ITriggerSession CreateSession(DbContext context, TriggerSessionConfiguration configuration, IServiceProvider? serviceProvider = null); + ITriggerSession CreateSession(DbContext context, TriggerSessionConfiguration configuration, IServiceProvider? serviceProvider = null); - ITriggerSession? Current { get; set; } - } + ITriggerSession? Current { get; set; } } diff --git a/src/EntityFrameworkCore.Triggered/ITriggerServiceProviderAccessor.cs b/src/EntityFrameworkCore.Triggered/ITriggerServiceProviderAccessor.cs index cb27c05..8528e5f 100644 --- a/src/EntityFrameworkCore.Triggered/ITriggerServiceProviderAccessor.cs +++ b/src/EntityFrameworkCore.Triggered/ITriggerServiceProviderAccessor.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public interface ITriggerServiceProviderAccessor { - public interface ITriggerServiceProviderAccessor - { - IServiceProvider GetTriggerServiceProvider(); - } + IServiceProvider GetTriggerServiceProvider(); } diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/CascadeBehavior.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/CascadeBehavior.cs index e24985c..873f2ea 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/CascadeBehavior.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/CascadeBehavior.cs @@ -1,17 +1,16 @@ -namespace EntityFrameworkCore.Triggered.Infrastructure +namespace EntityFrameworkCore.Triggered.Infrastructure; + +public enum CascadeBehavior { - public enum CascadeBehavior - { - /// - /// Disables cascading. Any changes made in will not raise additional triggers - /// - /// - /// No cascading is often not desired since it puts a soft restriction on . - /// - None, - /// - /// (Default) Triggers are only raised once per entity and change type . - /// - EntityAndType - } + /// + /// Disables cascading. Any changes made in will not raise additional triggers + /// + /// + /// No cascading is often not desired since it puts a soft restriction on . + /// + None, + /// + /// (Default) Triggers are only raised once per entity and change type . + /// + EntityAndType } diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs index f94588e..484ee47 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TriggersOptionExtension.cs @@ -7,314 +7,313 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace EntityFrameworkCore.Triggered.Infrastructure.Internal +namespace EntityFrameworkCore.Triggered.Infrastructure.Internal; + +public class TriggersOptionExtension : IDbContextOptionsExtension { - public class TriggersOptionExtension : IDbContextOptionsExtension + sealed class ExtensionInfo(IDbContextOptionsExtension extension) : DbContextOptionsExtensionInfo(extension) { - sealed class ExtensionInfo(IDbContextOptionsExtension extension) : DbContextOptionsExtensionInfo(extension) - { - private string? _logFragment; + private string? _logFragment; - public override bool IsDatabaseProvider => false; - public override string LogFragment + public override bool IsDatabaseProvider => false; + public override string LogFragment + { + get { - get - { - _logFragment ??= string.Empty; + _logFragment ??= string.Empty; - return _logFragment; - } + return _logFragment; } + } - public new TriggersOptionExtension Extension => (TriggersOptionExtension)base.Extension; + public new TriggersOptionExtension Extension => (TriggersOptionExtension)base.Extension; - public override void PopulateDebugInfo(IDictionary debugInfo) - { - ArgumentNullException.ThrowIfNull(debugInfo); + public override void PopulateDebugInfo(IDictionary debugInfo) + { + ArgumentNullException.ThrowIfNull(debugInfo); - debugInfo["Triggers:TriggersCount"] = (Extension._triggers?.Count() ?? 0).ToString(); - debugInfo["Triggers:TriggerTypesCount"] = (Extension._triggerTypes?.Count() ?? 0).ToString(); - debugInfo["Triggers:MaxCascadeCycles"] = Extension._maxCascadeCycles.ToString(); - debugInfo["Triggers:CascadeBehavior"] = Extension._cascadeBehavior.ToString(); - } + debugInfo["Triggers:TriggersCount"] = (Extension._triggers?.Count() ?? 0).ToString(); + debugInfo["Triggers:TriggerTypesCount"] = (Extension._triggerTypes?.Count() ?? 0).ToString(); + debugInfo["Triggers:MaxCascadeCycles"] = Extension._maxCascadeCycles.ToString(); + debugInfo["Triggers:CascadeBehavior"] = Extension._cascadeBehavior.ToString(); + } - public override int GetServiceProviderHashCode() - { - var hashCode = new HashCode(); + public override int GetServiceProviderHashCode() + { + var hashCode = new HashCode(); - if (Extension._triggers != null) + if (Extension._triggers != null) + { + foreach (var trigger in Extension._triggers) { - foreach (var trigger in Extension._triggers) - { - hashCode.Add(trigger); - } + hashCode.Add(trigger); } + } - if (Extension._triggerTypes != null) + if (Extension._triggerTypes != null) + { + foreach (var triggerType in Extension._triggerTypes) { - foreach (var triggerType in Extension._triggerTypes) - { - hashCode.Add(triggerType); - } + hashCode.Add(triggerType); } + } - hashCode.Add(Extension._maxCascadeCycles); - hashCode.Add(Extension._cascadeBehavior); + hashCode.Add(Extension._maxCascadeCycles); + hashCode.Add(Extension._cascadeBehavior); - if (Extension._serviceProviderTransform != null) - { - hashCode.Add(Extension._serviceProviderTransform); - } - - return hashCode.ToHashCode(); + if (Extension._serviceProviderTransform != null) + { + hashCode.Add(Extension._serviceProviderTransform); } - public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) - => other is ExtensionInfo otherInfo - && Enumerable.SequenceEqual(Extension._triggers ?? [], otherInfo.Extension._triggers ?? []) - && Enumerable.SequenceEqual(Extension._triggerTypes ?? [], otherInfo.Extension._triggerTypes ?? []) - && Extension._maxCascadeCycles == otherInfo.Extension._maxCascadeCycles - && Extension._cascadeBehavior == otherInfo.Extension._cascadeBehavior - && Extension._serviceProviderTransform == otherInfo.Extension._serviceProviderTransform; + return hashCode.ToHashCode(); } - private ExtensionInfo? _info; - private IEnumerable<(object typeOrInstance, ServiceLifetime lifetime)>? _triggers; - private IEnumerable _triggerTypes; - private int _maxCascadeCycles = 100; - private CascadeBehavior _cascadeBehavior = CascadeBehavior.EntityAndType; - private Func? _serviceProviderTransform; + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) + => other is ExtensionInfo otherInfo + && Enumerable.SequenceEqual(Extension._triggers ?? [], otherInfo.Extension._triggers ?? []) + && Enumerable.SequenceEqual(Extension._triggerTypes ?? [], otherInfo.Extension._triggerTypes ?? []) + && Extension._maxCascadeCycles == otherInfo.Extension._maxCascadeCycles + && Extension._cascadeBehavior == otherInfo.Extension._cascadeBehavior + && Extension._serviceProviderTransform == otherInfo.Extension._serviceProviderTransform; + } - public TriggersOptionExtension() - { - _triggerTypes = [ - typeof(IBeforeSaveTrigger<>), - typeof(IBeforeSaveAsyncTrigger<>), - typeof(IAfterSaveTrigger<>), - typeof(IAfterSaveAsyncTrigger<>), - typeof(IAfterSaveFailedTrigger<>), - typeof(IAfterSaveFailedAsyncTrigger<>), - typeof(IBeforeSaveStartingTrigger), - typeof(IBeforeSaveStartingAsyncTrigger), - typeof(IBeforeSaveCompletedTrigger), - typeof(IBeforeSaveCompletedAsyncTrigger), - typeof(IAfterSaveFailedStartingTrigger), - typeof(IAfterSaveFailedStartingAsyncTrigger), - typeof(IAfterSaveFailedCompletedTrigger), - typeof(IAfterSaveFailedCompletedAsyncTrigger), - typeof(IAfterSaveStartingTrigger), - typeof(IAfterSaveStartingAsyncTrigger), - typeof(IAfterSaveCompletedTrigger), - typeof(IAfterSaveCompletedAsyncTrigger) - ]; - } + private ExtensionInfo? _info; + private IEnumerable<(object typeOrInstance, ServiceLifetime lifetime)>? _triggers; + private IEnumerable _triggerTypes; + private int _maxCascadeCycles = 100; + private CascadeBehavior _cascadeBehavior = CascadeBehavior.EntityAndType; + private Func? _serviceProviderTransform; - public TriggersOptionExtension(TriggersOptionExtension copyFrom) - { - if (copyFrom._triggers != null) - { - _triggers = copyFrom._triggers; - } + public TriggersOptionExtension() + { + _triggerTypes = [ + typeof(IBeforeSaveTrigger<>), + typeof(IBeforeSaveAsyncTrigger<>), + typeof(IAfterSaveTrigger<>), + typeof(IAfterSaveAsyncTrigger<>), + typeof(IAfterSaveFailedTrigger<>), + typeof(IAfterSaveFailedAsyncTrigger<>), + typeof(IBeforeSaveStartingTrigger), + typeof(IBeforeSaveStartingAsyncTrigger), + typeof(IBeforeSaveCompletedTrigger), + typeof(IBeforeSaveCompletedAsyncTrigger), + typeof(IAfterSaveFailedStartingTrigger), + typeof(IAfterSaveFailedStartingAsyncTrigger), + typeof(IAfterSaveFailedCompletedTrigger), + typeof(IAfterSaveFailedCompletedAsyncTrigger), + typeof(IAfterSaveStartingTrigger), + typeof(IAfterSaveStartingAsyncTrigger), + typeof(IAfterSaveCompletedTrigger), + typeof(IAfterSaveCompletedAsyncTrigger) + ]; + } - _triggerTypes = copyFrom._triggerTypes; - _maxCascadeCycles = copyFrom._maxCascadeCycles; - _cascadeBehavior = copyFrom._cascadeBehavior; - _serviceProviderTransform = copyFrom._serviceProviderTransform; + public TriggersOptionExtension(TriggersOptionExtension copyFrom) + { + if (copyFrom._triggers != null) + { + _triggers = copyFrom._triggers; } - public DbContextOptionsExtensionInfo Info - => _info ??= new ExtensionInfo(this); + _triggerTypes = copyFrom._triggerTypes; + _maxCascadeCycles = copyFrom._maxCascadeCycles; + _cascadeBehavior = copyFrom._cascadeBehavior; + _serviceProviderTransform = copyFrom._serviceProviderTransform; + } - public int MaxCascadeCycles => _maxCascadeCycles; - public CascadeBehavior CascadeBehavior => _cascadeBehavior; - public IEnumerable<(object typeOrInstance, ServiceLifetime lifetime)> Triggers => _triggers ?? []; + public DbContextOptionsExtensionInfo Info + => _info ??= new ExtensionInfo(this); - public void ApplyServices(IServiceCollection services) - { - services.AddScoped(serviceProvider => new ApplicationTriggerServiceProviderAccessor(serviceProvider, _serviceProviderTransform)); - services.AddScoped(serviceProvider => serviceProvider.GetRequiredService()); - services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService()); + public int MaxCascadeCycles => _maxCascadeCycles; + public CascadeBehavior CascadeBehavior => _cascadeBehavior; + public IEnumerable<(object typeOrInstance, ServiceLifetime lifetime)> Triggers => _triggers ?? []; + + public void ApplyServices(IServiceCollection services) + { + services.AddScoped(serviceProvider => new ApplicationTriggerServiceProviderAccessor(serviceProvider, _serviceProviderTransform)); + services.AddScoped(serviceProvider => serviceProvider.GetRequiredService()); + services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService()); - services.TryAddSingleton(); + services.TryAddSingleton(); - services.AddScoped(); - services.AddScoped(serviceProvider => serviceProvider.GetRequiredService()); - services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService()); + services.AddScoped(); + services.AddScoped(serviceProvider => serviceProvider.GetRequiredService()); + services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService()); - services.AddScoped(); - services.AddScoped(serviceProvider => serviceProvider.GetRequiredService()); - services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService()); + services.AddScoped(); + services.AddScoped(serviceProvider => serviceProvider.GetRequiredService()); + services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService()); - services.AddScoped(); + services.AddScoped(); - services.TryAddScoped(); + services.TryAddScoped(); - services.Configure(triggerServiceOptions => { - triggerServiceOptions.MaxCascadeCycles = _maxCascadeCycles; - }); + services.Configure(triggerServiceOptions => { + triggerServiceOptions.MaxCascadeCycles = _maxCascadeCycles; + }); - var cascadeStrategyType = _cascadeBehavior switch { - CascadeBehavior.None => typeof(NoCascadeStrategy), - CascadeBehavior.EntityAndType => typeof(EntityAndTypeCascadeStrategy), - _ => throw new InvalidOperationException("Unsupported cascading mode") - }; + var cascadeStrategyType = _cascadeBehavior switch { + CascadeBehavior.None => typeof(NoCascadeStrategy), + CascadeBehavior.EntityAndType => typeof(EntityAndTypeCascadeStrategy), + _ => throw new InvalidOperationException("Unsupported cascading mode") + }; - services.TryAddTransient(typeof(ICascadeStrategy), cascadeStrategyType); + services.TryAddTransient(typeof(ICascadeStrategy), cascadeStrategyType); - if (_triggers != null && _triggerTypes != null) + if (_triggers != null && _triggerTypes != null) + { + foreach (var (typeOrInstance, lifetime) in _triggers) { - foreach (var (typeOrInstance, lifetime) in _triggers) - { - var (triggerServiceType, triggerServiceInstance) = typeOrInstance switch { - Type type => (type, null), - object instance => (instance.GetType(), instance), - _ => throw new InvalidOperationException("Unknown type registration") - }; + var (triggerServiceType, triggerServiceInstance) = typeOrInstance switch { + Type type => (type, null), + object instance => (instance.GetType(), instance), + _ => throw new InvalidOperationException("Unknown type registration") + }; - var instanceParamExpression = Expression.Parameter(typeof(object), "object"); + var instanceParamExpression = Expression.Parameter(typeof(object), "object"); - Func? triggerInstanceFactoryBuilder = null; + Func? triggerInstanceFactoryBuilder = null; - foreach (var triggerType in _triggerTypes.Distinct()) + foreach (var triggerType in _triggerTypes.Distinct()) + { + var triggerTypeImplementations = triggerType.IsGenericTypeDefinition + ? TypeHelpers.FindGenericInterfaces(triggerServiceType, triggerType) + : triggerServiceType.GetInterfaces().Where(x => x == triggerType); + + foreach (var triggerTypeImplementation in triggerTypeImplementations) { - var triggerTypeImplementations = triggerType.IsGenericTypeDefinition - ? TypeHelpers.FindGenericInterfaces(triggerServiceType, triggerType) - : triggerServiceType.GetInterfaces().Where(x => x == triggerType); - - foreach (var triggerTypeImplementation in triggerTypeImplementations) - { - triggerInstanceFactoryBuilder ??= - Expression.Lambda>( - Expression.New( - typeof(TriggerInstanceFactory<>).MakeGenericType(triggerServiceType).GetConstructor([typeof(object)])!, - instanceParamExpression - ), + triggerInstanceFactoryBuilder ??= + Expression.Lambda>( + Expression.New( + typeof(TriggerInstanceFactory<>).MakeGenericType(triggerServiceType).GetConstructor([typeof(object)])!, instanceParamExpression - ) - .Compile(); - - var triggerTypeImplementationFactoryType = typeof(ITriggerInstanceFactory<>).MakeGenericType(triggerTypeImplementation); - services.Add(new ServiceDescriptor(triggerTypeImplementationFactoryType, _ => triggerInstanceFactoryBuilder(triggerServiceInstance), lifetime)); - services.AddScoped(typeof(IResettableService), serviceProvider => serviceProvider.GetRequiredService(triggerTypeImplementationFactoryType)); - } + ), + instanceParamExpression + ) + .Compile(); + + var triggerTypeImplementationFactoryType = typeof(ITriggerInstanceFactory<>).MakeGenericType(triggerTypeImplementation); + services.Add(new ServiceDescriptor(triggerTypeImplementationFactoryType, _ => triggerInstanceFactoryBuilder(triggerServiceInstance), lifetime)); + services.AddScoped(typeof(IResettableService), serviceProvider => serviceProvider.GetRequiredService(triggerTypeImplementationFactoryType)); } } } } + } - public void Validate(IDbContextOptions options) { } + public void Validate(IDbContextOptions options) { } - protected TriggersOptionExtension Clone() => new(this); + protected TriggersOptionExtension Clone() => new(this); - private bool TypeIsValidTrigger(Type type) + private bool TypeIsValidTrigger(Type type) + { + if (TypeHelpers.FindGenericInterfaces(type, typeof(IBeforeSaveTrigger<>)) != null || TypeHelpers.FindGenericInterfaces(type, typeof(IAfterSaveTrigger<>)) != null) { - if (TypeHelpers.FindGenericInterfaces(type, typeof(IBeforeSaveTrigger<>)) != null || TypeHelpers.FindGenericInterfaces(type, typeof(IAfterSaveTrigger<>)) != null) - { - return true; - } - else if (_triggerTypes != null) - { - return _triggerTypes.Any(triggerType => TypeHelpers.FindGenericInterfaces(type, triggerType) != null); - } - else - { - return false; - } + return true; } - - public TriggersOptionExtension WithCascadeBehavior(CascadeBehavior cascadeBehavior) + else if (_triggerTypes != null) { - var clone = Clone(); - - clone._cascadeBehavior = cascadeBehavior; - - return clone; + return _triggerTypes.Any(triggerType => TypeHelpers.FindGenericInterfaces(type, triggerType) != null); } - - public TriggersOptionExtension WithMaxCascadeCycles(int maxCascadeCycles) + else { - var clone = Clone(); + return false; + } + } - clone._maxCascadeCycles = maxCascadeCycles; + public TriggersOptionExtension WithCascadeBehavior(CascadeBehavior cascadeBehavior) + { + var clone = Clone(); - return clone; - } + clone._cascadeBehavior = cascadeBehavior; - public TriggersOptionExtension WithAdditionalTrigger(Type triggerType, ServiceLifetime lifetime) - { - if (!TypeIsValidTrigger(triggerType)) - { - throw new ArgumentException("A trigger needs to implement either or both IBeforeSaveChangeTrigger or IAfterSaveChangeTriggerHandler", nameof(triggerType)); - } + return clone; + } - var clone = Clone(); - var triggerEnumerable = Enumerable.Repeat(((object)triggerType, lifetime), 1); + public TriggersOptionExtension WithMaxCascadeCycles(int maxCascadeCycles) + { + var clone = Clone(); - if (clone._triggers == null) - { - clone._triggers = triggerEnumerable; - } - else - { - clone._triggers = clone._triggers.Concat(triggerEnumerable); - } + clone._maxCascadeCycles = maxCascadeCycles; + return clone; + } - return clone; + public TriggersOptionExtension WithAdditionalTrigger(Type triggerType, ServiceLifetime lifetime) + { + if (!TypeIsValidTrigger(triggerType)) + { + throw new ArgumentException("A trigger needs to implement either or both IBeforeSaveChangeTrigger or IAfterSaveChangeTriggerHandler", nameof(triggerType)); } - public TriggersOptionExtension WithAdditionalTrigger(object instance) - { - ArgumentNullException.ThrowIfNull(instance); + var clone = Clone(); + var triggerEnumerable = Enumerable.Repeat(((object)triggerType, lifetime), 1); - if (!TypeIsValidTrigger(instance.GetType())) - { - throw new ArgumentException("A trigger needs to implement either or both IBeforeSaveChangeTrigger or IAfterSaveChangeTriggerHandler", nameof(instance)); - } + if (clone._triggers == null) + { + clone._triggers = triggerEnumerable; + } + else + { + clone._triggers = clone._triggers.Concat(triggerEnumerable); + } - var clone = Clone(); - var triggersEnumerable = Enumerable.Repeat((instance, ServiceLifetime.Singleton), 1); - if (clone._triggers == null) - { - clone._triggers = triggersEnumerable; - } - else - { - clone._triggers = clone._triggers.Concat(triggersEnumerable); - } + return clone; + } + public TriggersOptionExtension WithAdditionalTrigger(object instance) + { + ArgumentNullException.ThrowIfNull(instance); - return clone; + if (!TypeIsValidTrigger(instance.GetType())) + { + throw new ArgumentException("A trigger needs to implement either or both IBeforeSaveChangeTrigger or IAfterSaveChangeTriggerHandler", nameof(instance)); } - public TriggersOptionExtension WithAdditionalTriggerType(Type triggerType) + var clone = Clone(); + var triggersEnumerable = Enumerable.Repeat((instance, ServiceLifetime.Singleton), 1); + + if (clone._triggers == null) { - ArgumentNullException.ThrowIfNull(triggerType); + clone._triggers = triggersEnumerable; + } + else + { + clone._triggers = clone._triggers.Concat(triggersEnumerable); + } - var clone = Clone(); - var triggerTypesEnumerable = Enumerable.Repeat(triggerType, 1); + return clone; + } - if (clone._triggerTypes == null) - { - clone._triggerTypes = triggerTypesEnumerable; - } - else - { - clone._triggerTypes = clone._triggerTypes.Concat(triggerTypesEnumerable); - } + public TriggersOptionExtension WithAdditionalTriggerType(Type triggerType) + { + ArgumentNullException.ThrowIfNull(triggerType); - return clone; - } + var clone = Clone(); + var triggerTypesEnumerable = Enumerable.Repeat(triggerType, 1); - public TriggersOptionExtension WithApplicationScopedServiceProviderAccessor(Func serviceProviderTransform) + if (clone._triggerTypes == null) { - var clone = Clone(); - clone._serviceProviderTransform = serviceProviderTransform; - - return clone; + clone._triggerTypes = triggerTypesEnumerable; + } + else + { + clone._triggerTypes = clone._triggerTypes.Concat(triggerTypesEnumerable); } + + + return clone; + } + + public TriggersOptionExtension WithApplicationScopedServiceProviderAccessor(Func serviceProviderTransform) + { + var clone = Clone(); + clone._serviceProviderTransform = serviceProviderTransform; + + return clone; } } diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs index 306ceb7..460143a 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/Internal/TypeHelpers.cs @@ -1,19 +1,18 @@ -namespace EntityFrameworkCore.Triggered.Infrastructure.Internal +namespace EntityFrameworkCore.Triggered.Infrastructure.Internal; + +public static class TypeHelpers { - public static class TypeHelpers + public static IEnumerable FindGenericInterfaces(Type type, Type interfaceType) + => type.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType); + + public static IEnumerable EnumerateTypeHierarchy(Type type) { - public static IEnumerable FindGenericInterfaces(Type type, Type interfaceType) - => type.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType); + Type? nextType = type; - public static IEnumerable EnumerateTypeHierarchy(Type type) + while (nextType is not null) { - Type? nextType = type; - - while (nextType is not null) - { - yield return nextType; - nextType = nextType.BaseType; - } while (nextType != null) ; - } + yield return nextType; + nextType = nextType.BaseType; + } while (nextType != null) ; } } diff --git a/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs b/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs index c77959d..4884392 100644 --- a/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs +++ b/src/EntityFrameworkCore.Triggered/Infrastructure/TriggersContextOptionsBuilder.cs @@ -3,48 +3,47 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; -namespace EntityFrameworkCore.Triggered.Infrastructure +namespace EntityFrameworkCore.Triggered.Infrastructure; + +public class TriggersContextOptionsBuilder(DbContextOptionsBuilder optionsBuilder) { - public class TriggersContextOptionsBuilder(DbContextOptionsBuilder optionsBuilder) - { - readonly DbContextOptionsBuilder _optionsBuilder = optionsBuilder ?? throw new ArgumentNullException(nameof(optionsBuilder)); + readonly DbContextOptionsBuilder _optionsBuilder = optionsBuilder ?? throw new ArgumentNullException(nameof(optionsBuilder)); - public TriggersContextOptionsBuilder AddTrigger() - => AddTrigger(ServiceLifetime.Transient); + public TriggersContextOptionsBuilder AddTrigger() + => AddTrigger(ServiceLifetime.Transient); - public TriggersContextOptionsBuilder AddTrigger(ServiceLifetime lifetime) - => AddTrigger(typeof(TTrigger), lifetime); + public TriggersContextOptionsBuilder AddTrigger(ServiceLifetime lifetime) + => AddTrigger(typeof(TTrigger), lifetime); - public TriggersContextOptionsBuilder AddTrigger(Type triggerType, ServiceLifetime lifetime) - => WithOption(e => e.WithAdditionalTrigger(triggerType, lifetime)); + public TriggersContextOptionsBuilder AddTrigger(Type triggerType, ServiceLifetime lifetime) + => WithOption(e => e.WithAdditionalTrigger(triggerType, lifetime)); - public TriggersContextOptionsBuilder AddTrigger(object trigger) - => WithOption(e => e.WithAdditionalTrigger(trigger)); + public TriggersContextOptionsBuilder AddTrigger(object trigger) + => WithOption(e => e.WithAdditionalTrigger(trigger)); - public TriggersContextOptionsBuilder CascadeBehavior(CascadeBehavior cascadeBehavior = Infrastructure.CascadeBehavior.EntityAndType) - => WithOption(e => e.WithCascadeBehavior(cascadeBehavior)); + public TriggersContextOptionsBuilder CascadeBehavior(CascadeBehavior cascadeBehavior = Infrastructure.CascadeBehavior.EntityAndType) + => WithOption(e => e.WithCascadeBehavior(cascadeBehavior)); - public TriggersContextOptionsBuilder MaxCascadeCycles(int maxCascadingCycles = 100) - => WithOption(e => e.WithMaxCascadeCycles(maxCascadingCycles)); + public TriggersContextOptionsBuilder MaxCascadeCycles(int maxCascadingCycles = 100) + => WithOption(e => e.WithMaxCascadeCycles(maxCascadingCycles)); - public TriggersContextOptionsBuilder AddTriggerType(Type triggerType) - => WithOption(e => e.WithAdditionalTriggerType(triggerType)); + public TriggersContextOptionsBuilder AddTriggerType(Type triggerType) + => WithOption(e => e.WithAdditionalTriggerType(triggerType)); - public TriggersContextOptionsBuilder UseApplicationScopedServiceProviderAccessor(Func serviceProviderTransform) - => WithOption(e => e.WithApplicationScopedServiceProviderAccessor(serviceProviderTransform)); + public TriggersContextOptionsBuilder UseApplicationScopedServiceProviderAccessor(Func serviceProviderTransform) + => WithOption(e => e.WithApplicationScopedServiceProviderAccessor(serviceProviderTransform)); - /// - /// Sets an option by cloning the extension used to store the settings. This ensures the builder - /// does not modify options that are already in use elsewhere. - /// - /// An action to set the option. - /// The same builder instance so that multiple calls can be chained. - protected virtual TriggersContextOptionsBuilder WithOption(Func setAction) - { - ((IDbContextOptionsBuilderInfrastructure)_optionsBuilder).AddOrUpdateExtension( - setAction(_optionsBuilder.Options.FindExtension() ?? new TriggersOptionExtension())); + /// + /// Sets an option by cloning the extension used to store the settings. This ensures the builder + /// does not modify options that are already in use elsewhere. + /// + /// An action to set the option. + /// The same builder instance so that multiple calls can be chained. + protected virtual TriggersContextOptionsBuilder WithOption(Func setAction) + { + ((IDbContextOptionsBuilderInfrastructure)_optionsBuilder).AddOrUpdateExtension( + setAction(_optionsBuilder.Options.FindExtension() ?? new TriggersOptionExtension())); - return this; - } + return this; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs b/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs index be5f818..a106f42 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ApplicationTriggerServiceProviderAccessor.cs @@ -1,80 +1,79 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; -namespace EntityFrameworkCore.Triggered.Internal -{ - public sealed class ApplicationTriggerServiceProviderAccessor : ITriggerServiceProviderAccessor, IDisposable, IResettableService - { - readonly IServiceProvider _internalServiceProvider; - readonly IServiceProvider? _fallbackApplicationServiceProvider; - readonly Func? _scopedServiceProviderTransform; +namespace EntityFrameworkCore.Triggered.Internal; - IServiceScope? _serviceScope; - IServiceProvider? _applicationScopedServiceProvider; +public sealed class ApplicationTriggerServiceProviderAccessor : ITriggerServiceProviderAccessor, IDisposable, IResettableService +{ + readonly IServiceProvider _internalServiceProvider; + readonly IServiceProvider? _fallbackApplicationServiceProvider; + readonly Func? _scopedServiceProviderTransform; - public ApplicationTriggerServiceProviderAccessor(IServiceProvider internalServiceProvider, Func? scopedServiceProviderTransform) - { - ArgumentNullException.ThrowIfNull(internalServiceProvider); + IServiceScope? _serviceScope; + IServiceProvider? _applicationScopedServiceProvider; - var dbContextOptions = internalServiceProvider.GetRequiredService(); - var coreOptionsExtension = dbContextOptions.FindExtension() ?? throw new InvalidOperationException("No coreOptionsExtension configured"); + public ApplicationTriggerServiceProviderAccessor(IServiceProvider internalServiceProvider, Func? scopedServiceProviderTransform) + { + ArgumentNullException.ThrowIfNull(internalServiceProvider); - _internalServiceProvider = internalServiceProvider; - if (scopedServiceProviderTransform == null) - { - _fallbackApplicationServiceProvider = coreOptionsExtension.ApplicationServiceProvider; - } + var dbContextOptions = internalServiceProvider.GetRequiredService(); + var coreOptionsExtension = dbContextOptions.FindExtension() ?? throw new InvalidOperationException("No coreOptionsExtension configured"); - _scopedServiceProviderTransform = scopedServiceProviderTransform; + _internalServiceProvider = internalServiceProvider; + if (scopedServiceProviderTransform == null) + { + _fallbackApplicationServiceProvider = coreOptionsExtension.ApplicationServiceProvider; } - public void SetTriggerServiceProvider(IServiceProvider serviceProvider) => _applicationScopedServiceProvider = serviceProvider; + _scopedServiceProviderTransform = scopedServiceProviderTransform; + } + + public void SetTriggerServiceProvider(IServiceProvider serviceProvider) => _applicationScopedServiceProvider = serviceProvider; - public IServiceProvider GetTriggerServiceProvider() + public IServiceProvider GetTriggerServiceProvider() + { + if (_applicationScopedServiceProvider == null) { - if (_applicationScopedServiceProvider == null) + if (_fallbackApplicationServiceProvider != null) { - if (_fallbackApplicationServiceProvider != null) - { - _applicationScopedServiceProvider = _fallbackApplicationServiceProvider; - } - else if (_scopedServiceProviderTransform != null) - { - var dbContextOptions = _internalServiceProvider.GetRequiredService(); - var coreOptionsExtension = dbContextOptions.FindExtension(); - var serviceProvider = coreOptionsExtension!.ApplicationServiceProvider ?? _internalServiceProvider; - - _applicationScopedServiceProvider = _scopedServiceProviderTransform(serviceProvider); - } - else - { - var dbContext = _internalServiceProvider.GetRequiredService().Context; - _applicationScopedServiceProvider = new HybridServiceProvider(_internalServiceProvider, dbContext); - } - + _applicationScopedServiceProvider = _fallbackApplicationServiceProvider; } + else if (_scopedServiceProviderTransform != null) + { + var dbContextOptions = _internalServiceProvider.GetRequiredService(); + var coreOptionsExtension = dbContextOptions.FindExtension(); + var serviceProvider = coreOptionsExtension!.ApplicationServiceProvider ?? _internalServiceProvider; - return _applicationScopedServiceProvider; - } - - public void Dispose() - => _serviceScope?.Dispose(); - - public void ResetState() - { - if (_serviceScope != null) + _applicationScopedServiceProvider = _scopedServiceProviderTransform(serviceProvider); + } + else { - _serviceScope.Dispose(); - _serviceScope = null; + var dbContext = _internalServiceProvider.GetRequiredService().Context; + _applicationScopedServiceProvider = new HybridServiceProvider(_internalServiceProvider, dbContext); } - _applicationScopedServiceProvider = null; } - public Task ResetStateAsync(CancellationToken cancellationToken = default) + return _applicationScopedServiceProvider; + } + + public void Dispose() + => _serviceScope?.Dispose(); + + public void ResetState() + { + if (_serviceScope != null) { - ResetState(); - return Task.CompletedTask; + _serviceScope.Dispose(); + _serviceScope = null; } + + _applicationScopedServiceProvider = null; + } + + public Task ResetStateAsync(CancellationToken cancellationToken = default) + { + ResetState(); + return Task.CompletedTask; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/AsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/AsyncTriggerDescriptor.cs index 0891356..9a49733 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/AsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/AsyncTriggerDescriptor.cs @@ -1,34 +1,33 @@ using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public class AsyncTriggerDescriptor { - public class AsyncTriggerDescriptor + readonly IAsyncTriggerTypeDescriptor _triggerTypeDescriptor; + readonly object _trigger; + readonly int _priority; + + public AsyncTriggerDescriptor(IAsyncTriggerTypeDescriptor triggerTypeDescriptor, object trigger) { - readonly IAsyncTriggerTypeDescriptor _triggerTypeDescriptor; - readonly object _trigger; - readonly int _priority; + _triggerTypeDescriptor = triggerTypeDescriptor ?? throw new ArgumentNullException(nameof(triggerTypeDescriptor)); + _trigger = trigger ?? throw new ArgumentNullException(nameof(trigger)); - public AsyncTriggerDescriptor(IAsyncTriggerTypeDescriptor triggerTypeDescriptor, object trigger) + if (_trigger is ITriggerPriority triggerPriority) { - _triggerTypeDescriptor = triggerTypeDescriptor ?? throw new ArgumentNullException(nameof(triggerTypeDescriptor)); - _trigger = trigger ?? throw new ArgumentNullException(nameof(trigger)); - - if (_trigger is ITriggerPriority triggerPriority) - { - _priority = triggerPriority.Priority; - } - else - { - _priority = 0; - } + _priority = triggerPriority.Priority; } + else + { + _priority = 0; + } + } - public IAsyncTriggerTypeDescriptor TypeDescriptor => _triggerTypeDescriptor; - public object Trigger => _trigger; - public int Priority => _priority; + public IAsyncTriggerTypeDescriptor TypeDescriptor => _triggerTypeDescriptor; + public object Trigger => _trigger; + public int Priority => _priority; - public Task Invoke(object triggerContext, Exception? exception, CancellationToken cancellationToken) - => _triggerTypeDescriptor.Invoke(_trigger, triggerContext, exception, cancellationToken); + public Task Invoke(object triggerContext, Exception? exception, CancellationToken cancellationToken) + => _triggerTypeDescriptor.Invoke(_trigger, triggerContext, exception, cancellationToken); - } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/EntityAndTypeCascadeStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/EntityAndTypeCascadeStrategy.cs index b9a81f2..9732505 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/EntityAndTypeCascadeStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/EntityAndTypeCascadeStrategy.cs @@ -1,10 +1,9 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace EntityFrameworkCore.Triggered.Internal.CascadeStrategies +namespace EntityFrameworkCore.Triggered.Internal.CascadeStrategies; + +public class EntityAndTypeCascadeStrategy : ICascadeStrategy { - public class EntityAndTypeCascadeStrategy : ICascadeStrategy - { - public bool CanCascade(EntityEntry entry, ChangeType changeType, TriggerContextDescriptor previousTriggerContextDescriptor) - => changeType != previousTriggerContextDescriptor.ChangeType; - } + public bool CanCascade(EntityEntry entry, ChangeType changeType, TriggerContextDescriptor previousTriggerContextDescriptor) + => changeType != previousTriggerContextDescriptor.ChangeType; } diff --git a/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/ICascadeStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/ICascadeStrategy.cs index e52c8a3..3a5e6f7 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/ICascadeStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/ICascadeStrategy.cs @@ -1,9 +1,8 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace EntityFrameworkCore.Triggered.Internal.CascadeStrategies +namespace EntityFrameworkCore.Triggered.Internal.CascadeStrategies; + +public interface ICascadeStrategy { - public interface ICascadeStrategy - { - bool CanCascade(EntityEntry entry, ChangeType changeType, TriggerContextDescriptor previousTriggerContextDescriptor); - } + bool CanCascade(EntityEntry entry, ChangeType changeType, TriggerContextDescriptor previousTriggerContextDescriptor); } diff --git a/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/NoCascadeStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/NoCascadeStrategy.cs index d6865d4..2fbc8b0 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/NoCascadeStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/CascadeStrategies/NoCascadeStrategy.cs @@ -1,10 +1,9 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace EntityFrameworkCore.Triggered.Internal.CascadeStrategies +namespace EntityFrameworkCore.Triggered.Internal.CascadeStrategies; + +public class NoCascadeStrategy : ICascadeStrategy { - public class NoCascadeStrategy : ICascadeStrategy - { - public bool CanCascade(EntityEntry entry, ChangeType changeType, TriggerContextDescriptor previousTriggerContextDescriptor) - => false; - } + public bool CanCascade(EntityEntry entry, ChangeType changeType, TriggerContextDescriptor previousTriggerContextDescriptor) + => false; } diff --git a/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs index 414c454..fdf56a8 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/CascadingTriggerContextDiscoveryStrategy.cs @@ -1,60 +1,59 @@ using Microsoft.Extensions.Logging; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public class CascadingTriggerContextDiscoveryStrategy(string name, bool skipDetectedChanges) : ITriggerContextDiscoveryStrategy { - public class CascadingTriggerContextDiscoveryStrategy(string name, bool skipDetectedChanges) : ITriggerContextDiscoveryStrategy - { - readonly static Action _discoveryStarted = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "Discovered"), - "Starting trigger discovery for {name} with a max cascade of {maxCascadingCycles}"); + readonly static Action _discoveryStarted = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "Discovered"), + "Starting trigger discovery for {name} with a max cascade of {maxCascadingCycles}"); - readonly static Action _changesDetected = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "Discovered"), - "Discovered changes: {changes} for {name}. Iteration ({iteration}/{maxCascadingCycles})"); + readonly static Action _changesDetected = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "Discovered"), + "Discovered changes: {changes} for {name}. Iteration ({iteration}/{maxCascadingCycles})"); - readonly string _name = name ?? throw new ArgumentNullException(nameof(name)); - readonly bool _skipDetectedChanges = skipDetectedChanges; + readonly string _name = name ?? throw new ArgumentNullException(nameof(name)); + readonly bool _skipDetectedChanges = skipDetectedChanges; - public IEnumerable> Discover(TriggerSessionConfiguration configuration, TriggerContextTracker tracker, ILogger logger) - { - var maxCascadingCycles = configuration.MaxCascadeCycles; - _discoveryStarted(logger, _name, maxCascadingCycles, null); + public IEnumerable> Discover(TriggerSessionConfiguration configuration, TriggerContextTracker tracker, ILogger logger) + { + var maxCascadingCycles = configuration.MaxCascadeCycles; + _discoveryStarted(logger, _name, maxCascadingCycles, null); - var iteration = 0; - while (true) + var iteration = 0; + while (true) + { + if (iteration > maxCascadingCycles) { - if (iteration > maxCascadingCycles) - { - throw new InvalidOperationException("MaxCascadingCycle was reached"); - } + throw new InvalidOperationException("MaxCascadingCycle was reached"); + } - var changes = tracker.DiscoverChanges(); + var changes = tracker.DiscoverChanges(); - // In case someone made a call to TriggerSession.DetectChanges, prior to calling RaiseBeforeSaveTriggers, we want to make sure that we include that discovery result in the first iteration - if (iteration == 0 && !_skipDetectedChanges) - { - changes = tracker.DiscoveredChanges!; - } - - if (changes.Any()) - { - if (logger.IsEnabled(LogLevel.Debug)) - { - changes = changes.ToList(); - _changesDetected(logger, changes.Count(), _name, iteration, maxCascadingCycles, null); - } + // In case someone made a call to TriggerSession.DetectChanges, prior to calling RaiseBeforeSaveTriggers, we want to make sure that we include that discovery result in the first iteration + if (iteration == 0 && !_skipDetectedChanges) + { + changes = tracker.DiscoveredChanges!; + } - yield return changes; - } - else + if (changes.Any()) + { + if (logger.IsEnabled(LogLevel.Debug)) { - break; + changes = changes.ToList(); + _changesDetected(logger, changes.Count(), _name, iteration, maxCascadingCycles, null); } - iteration++; + yield return changes; + } + else + { + break; } + + iteration++; } } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveAsyncTriggerDescriptor.cs index ede6505..5367539 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveAsyncTriggerDescriptor.cs @@ -1,28 +1,27 @@ using System.Diagnostics; -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors; + +public sealed class AfterSaveAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor { - public sealed class AfterSaveAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor - { - readonly Func _invocationDelegate; - readonly Type _triggerType; + readonly Func _invocationDelegate; + readonly Type _triggerType; - public AfterSaveAsyncTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IAfterSaveAsyncTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IAfterSaveAsyncTrigger.AfterSaveAsync)); + public AfterSaveAsyncTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IAfterSaveAsyncTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IAfterSaveAsyncTrigger.AfterSaveAsync)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) - { - Debug.Assert(exception == null); + public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) + { + Debug.Assert(exception == null); - return _invocationDelegate(trigger, triggerContext, cancellationToken); - } + return _invocationDelegate(trigger, triggerContext, cancellationToken); } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptor.cs index 4d1933e..7c3a721 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptor.cs @@ -1,23 +1,22 @@ -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors; + +public sealed class AfterSaveFailedAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor { - public sealed class AfterSaveFailedAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor - { - readonly Func _invocationDelegate; - readonly Type _triggerType; + readonly Func _invocationDelegate; + readonly Type _triggerType; - public AfterSaveFailedAsyncTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IAfterSaveFailedAsyncTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IAfterSaveFailedAsyncTrigger.AfterSaveFailedAsync)); + public AfterSaveFailedAsyncTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IAfterSaveFailedAsyncTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IAfterSaveFailedAsyncTrigger.AfterSaveFailedAsync)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegateWithException(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegateWithException(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) - => _invocationDelegate(trigger, triggerContext, exception, cancellationToken); + public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) + => _invocationDelegate(trigger, triggerContext, exception, cancellationToken); - } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs index 4ae4043..4cb209b 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveFailedTriggerDescriptor.cs @@ -1,22 +1,21 @@ -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors; + +public sealed class AfterSaveFailedTriggerDescriptor : ITriggerTypeDescriptor { - public sealed class AfterSaveFailedTriggerDescriptor : ITriggerTypeDescriptor - { - readonly Action _invocationDelegate; - readonly Type _triggerType; + readonly Action _invocationDelegate; + readonly Type _triggerType; - public AfterSaveFailedTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IAfterSaveFailedTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IAfterSaveFailedTrigger.AfterSaveFailed)); + public AfterSaveFailedTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IAfterSaveFailedTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IAfterSaveFailedTrigger.AfterSaveFailed)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegateWithException(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegateWithException(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public void Invoke(object trigger, object triggerContext, Exception? exception) - => _invocationDelegate(trigger, triggerContext, exception); - } + public void Invoke(object trigger, object triggerContext, Exception? exception) + => _invocationDelegate(trigger, triggerContext, exception); } diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs index b305198..13580df 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/AfterSaveTriggerDescriptor.cs @@ -1,28 +1,27 @@ using System.Diagnostics; -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors; + +public sealed class AfterSaveTriggerDescriptor : ITriggerTypeDescriptor { - public sealed class AfterSaveTriggerDescriptor : ITriggerTypeDescriptor - { - readonly Action _invocationDelegate; - readonly Type _triggerType; + readonly Action _invocationDelegate; + readonly Type _triggerType; - public AfterSaveTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IAfterSaveTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IAfterSaveTrigger.AfterSave)); + public AfterSaveTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IAfterSaveTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IAfterSaveTrigger.AfterSave)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public void Invoke(object trigger, object triggerContext, Exception? exception) - { - Debug.Assert(exception == null); + public void Invoke(object trigger, object triggerContext, Exception? exception) + { + Debug.Assert(exception == null); - _invocationDelegate(trigger, triggerContext); - } + _invocationDelegate(trigger, triggerContext); } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptor.cs index a9e828e..04357de 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptor.cs @@ -1,28 +1,27 @@ using System.Diagnostics; -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors; + +public sealed class BeforeSaveAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor { - public sealed class BeforeSaveAsyncTriggerDescriptor : IAsyncTriggerTypeDescriptor - { - readonly Func _invocationDelegate; - readonly Type _triggerType; + readonly Func _invocationDelegate; + readonly Type _triggerType; - public BeforeSaveAsyncTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IBeforeSaveAsyncTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IBeforeSaveAsyncTrigger.BeforeSaveAsync)); + public BeforeSaveAsyncTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IBeforeSaveAsyncTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IBeforeSaveAsyncTrigger.BeforeSaveAsync)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) - { - Debug.Assert(exception == null); + public Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) + { + Debug.Assert(exception == null); - return _invocationDelegate(trigger, triggerContext, cancellationToken); - } + return _invocationDelegate(trigger, triggerContext, cancellationToken); } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs index 7741510..9c7677d 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/BeforeSaveTriggerDescriptor.cs @@ -1,28 +1,27 @@ using System.Diagnostics; -namespace EntityFrameworkCore.Triggered.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Internal.Descriptors; + +public sealed class BeforeSaveTriggerDescriptor : ITriggerTypeDescriptor { - public sealed class BeforeSaveTriggerDescriptor : ITriggerTypeDescriptor - { - readonly Action _invocationDelegate; - readonly Type _triggerType; + readonly Action _invocationDelegate; + readonly Type _triggerType; - public BeforeSaveTriggerDescriptor(Type entityType) - { - var triggerType = typeof(IBeforeSaveTrigger<>).MakeGenericType(entityType); - var triggerMethod = triggerType.GetMethod(nameof(IBeforeSaveTrigger.BeforeSave)); + public BeforeSaveTriggerDescriptor(Type entityType) + { + var triggerType = typeof(IBeforeSaveTrigger<>).MakeGenericType(entityType); + var triggerMethod = triggerType.GetMethod(nameof(IBeforeSaveTrigger.BeforeSave)); - _triggerType = triggerType; - _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); - } + _triggerType = triggerType; + _invocationDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(triggerType, entityType, triggerMethod!); + } - public Type TriggerType => _triggerType; + public Type TriggerType => _triggerType; - public void Invoke(object trigger, object triggerContext, Exception? exception) - { - Debug.Assert(exception == null); + public void Invoke(object trigger, object triggerContext, Exception? exception) + { + Debug.Assert(exception == null); - _invocationDelegate(trigger, triggerContext); - } + _invocationDelegate(trigger, triggerContext); } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/IAsyncTriggerTypeDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/IAsyncTriggerTypeDescriptor.cs index df5f262..aae5e1c 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/IAsyncTriggerTypeDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/IAsyncTriggerTypeDescriptor.cs @@ -1,9 +1,7 @@ -namespace EntityFrameworkCore.Triggered.Internal.Descriptors -{ - public interface IAsyncTriggerTypeDescriptor - { - Type TriggerType { get; } - Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken); - } +namespace EntityFrameworkCore.Triggered.Internal.Descriptors; +public interface IAsyncTriggerTypeDescriptor +{ + Type TriggerType { get; } + Task Invoke(object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken); } diff --git a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/ITriggerTypeDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/ITriggerTypeDescriptor.cs index 8561ca8..789a934 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/Descriptors/ITriggerTypeDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/Descriptors/ITriggerTypeDescriptor.cs @@ -1,10 +1,8 @@ -namespace EntityFrameworkCore.Triggered.Internal.Descriptors -{ +namespace EntityFrameworkCore.Triggered.Internal.Descriptors; - public interface ITriggerTypeDescriptor - { - Type TriggerType { get; } - void Invoke(object trigger, object triggerContext, Exception? exception); - } +public interface ITriggerTypeDescriptor +{ + Type TriggerType { get; } + void Invoke(object trigger, object triggerContext, Exception? exception); } diff --git a/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs b/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs index e1f35a3..8e4c55f 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/EntityStateBagManager.cs @@ -1,18 +1,17 @@ -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public sealed class EntityBagStateManager { - public sealed class EntityBagStateManager - { - private readonly Dictionary> _resolvedBags = []; + private readonly Dictionary> _resolvedBags = []; - public IDictionary GetForEntity(object entity) + public IDictionary GetForEntity(object entity) + { + if (!_resolvedBags.TryGetValue(entity, out var bag)) { - if (!_resolvedBags.TryGetValue(entity, out var bag)) - { - bag = new Dictionary(); - _resolvedBags.Add(entity, bag); - } - - return bag; + bag = new Dictionary(); + _resolvedBags.Add(entity, bag); } + + return bag; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs b/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs index a85fdb0..40a6a4a 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/HybridServiceProvider.cs @@ -1,27 +1,26 @@ using Microsoft.EntityFrameworkCore; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public sealed class HybridServiceProvider(IServiceProvider serviceProvider, DbContext dbContext) : IServiceProvider { - public sealed class HybridServiceProvider(IServiceProvider serviceProvider, DbContext dbContext) : IServiceProvider - { - readonly DbContext _dbContext = dbContext; - readonly IServiceProvider _serviceProvider = serviceProvider; + readonly DbContext _dbContext = dbContext; + readonly IServiceProvider _serviceProvider = serviceProvider; - public object? GetService(Type serviceType) + public object? GetService(Type serviceType) + { + // Starting from EF Core Triggered v3 we prefer the captured DbContext over our registry + if (serviceType.IsAssignableFrom(_dbContext.GetType())) { - // Starting from EF Core Triggered v3 we prefer the captured DbContext over our registry - if (serviceType.IsAssignableFrom(_dbContext.GetType())) - { - return _dbContext; - } - - var result = _serviceProvider.GetService(serviceType); - if (result is not null) - { - return result; - } + return _dbContext; + } - return default; + var result = _serviceProvider.GetService(serviceType); + if (result is not null) + { + return result; } + + return default; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/ITriggerContextDiscoveryStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/ITriggerContextDiscoveryStrategy.cs index b621680..6755b6f 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ITriggerContextDiscoveryStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ITriggerContextDiscoveryStrategy.cs @@ -1,9 +1,8 @@ using Microsoft.Extensions.Logging; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public interface ITriggerContextDiscoveryStrategy { - public interface ITriggerContextDiscoveryStrategy - { - IEnumerable> Discover(TriggerSessionConfiguration configuration, TriggerContextTracker tracker, ILogger logger); - } + IEnumerable> Discover(TriggerSessionConfiguration configuration, TriggerContextTracker tracker, ILogger logger); } diff --git a/src/EntityFrameworkCore.Triggered/Internal/ITriggerDiscoveryService.cs b/src/EntityFrameworkCore.Triggered/Internal/ITriggerDiscoveryService.cs index 58d52ce..64bb53c 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ITriggerDiscoveryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ITriggerDiscoveryService.cs @@ -1,15 +1,14 @@ using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public interface ITriggerDiscoveryService { - public interface ITriggerDiscoveryService - { - IEnumerable DiscoverAsyncTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory); + IEnumerable DiscoverAsyncTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory); - IEnumerable DiscoverTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory); + IEnumerable DiscoverTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory); - IEnumerable DiscoverTriggers(); + IEnumerable DiscoverTriggers(); - public IServiceProvider ServiceProvider { get; set; } - } + public IServiceProvider ServiceProvider { get; set; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs b/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs index c229a11..884cd4e 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/ITriggerTypeRegistryService.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public interface ITriggerTypeRegistryService { - public interface ITriggerTypeRegistryService - { - TriggerTypeRegistry ResolveRegistry(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory); - } + TriggerTypeRegistry ResolveRegistry(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory); } \ No newline at end of file diff --git a/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs b/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs index b23b270..2a2ceac 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs @@ -1,26 +1,25 @@ using Microsoft.Extensions.Logging; -namespace EntityFrameworkCore.Triggered.Internal -{ - public class NonCascadingTriggerContextDiscoveryStrategy(string name) : ITriggerContextDiscoveryStrategy - { - readonly static Action _changesDetected = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "Discovered"), - "Discovered changes: {changes} for {name}"); +namespace EntityFrameworkCore.Triggered.Internal; - readonly string _name = name ?? throw new ArgumentNullException(nameof(name)); +public class NonCascadingTriggerContextDiscoveryStrategy(string name) : ITriggerContextDiscoveryStrategy +{ + readonly static Action _changesDetected = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "Discovered"), + "Discovered changes: {changes} for {name}"); - public IEnumerable> Discover(TriggerSessionConfiguration configuration, TriggerContextTracker tracker, ILogger logger) - { - var changes = tracker.DiscoveredChanges ?? throw new InvalidOperationException("Trigger discovery process has not yet started. Please ensure that TriggerSession.DiscoverChanges() or TriggerSession.RaiseBeforeSaveTriggers() has been called"); + readonly string _name = name ?? throw new ArgumentNullException(nameof(name)); - if (logger.IsEnabled(LogLevel.Debug)) - { - _changesDetected(logger, changes.Count(), _name, null); - } + public IEnumerable> Discover(TriggerSessionConfiguration configuration, TriggerContextTracker tracker, ILogger logger) + { + var changes = tracker.DiscoveredChanges ?? throw new InvalidOperationException("Trigger discovery process has not yet started. Please ensure that TriggerSession.DiscoverChanges() or TriggerSession.RaiseBeforeSaveTriggers() has been called"); - return Enumerable.Repeat(changes, 1); + if (logger.IsEnabled(LogLevel.Debug)) + { + _changesDetected(logger, changes.Count(), _name, null); } + + return Enumerable.Repeat(changes, 1); } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs index ff9adab..6aa1cbe 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs @@ -1,39 +1,38 @@ using System.Collections.Concurrent; using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public readonly struct TriggerContextDescriptor(EntityEntry entityEntry, ChangeType changeType) { - public readonly struct TriggerContextDescriptor(EntityEntry entityEntry, ChangeType changeType) - { - readonly static ConcurrentDictionary> _cachedTriggerContextFactories = new(); + readonly static ConcurrentDictionary> _cachedTriggerContextFactories = new(); - readonly EntityEntry _entityEntry = entityEntry; - readonly ChangeType _changeType = changeType; - readonly PropertyValues? _originalValues = entityEntry.OriginalValues.Clone(); + readonly EntityEntry _entityEntry = entityEntry; + readonly ChangeType _changeType = changeType; + readonly PropertyValues? _originalValues = entityEntry.OriginalValues.Clone(); - public ChangeType ChangeType => _changeType; - public object Entity => _entityEntry!.Entity; - public Type EntityType => _entityEntry!.Entity.GetType(); + public ChangeType ChangeType => _changeType; + public object Entity => _entityEntry!.Entity; + public Type EntityType => _entityEntry!.Entity.GetType(); - public object GetTriggerContext(EntityBagStateManager entityBagStateManager) - { - var entityEntry = _entityEntry; - var changeType = _changeType; - var originalValues = _originalValues; + public object GetTriggerContext(EntityBagStateManager entityBagStateManager) + { + var entityEntry = _entityEntry; + var changeType = _changeType; + var originalValues = _originalValues; - if (entityEntry == null) - { - throw new InvalidOperationException("No initialized"); - } + if (entityEntry == null) + { + throw new InvalidOperationException("No initialized"); + } - var entityType = entityEntry.Entity.GetType(); + var entityType = entityEntry.Entity.GetType(); - var triggerContextFactory = _cachedTriggerContextFactories.GetOrAdd(entityType, entityType => - (Func)typeof(TriggerContextFactory<>).MakeGenericType(entityType) - !.GetMethod(nameof(TriggerContextFactory.Activate)) - !.CreateDelegate(typeof(Func))); + var triggerContextFactory = _cachedTriggerContextFactories.GetOrAdd(entityType, entityType => + (Func)typeof(TriggerContextFactory<>).MakeGenericType(entityType) + !.GetMethod(nameof(TriggerContextFactory.Activate)) + !.CreateDelegate(typeof(Func))); - return triggerContextFactory(entityEntry, originalValues, changeType, entityBagStateManager); - } + return triggerContextFactory(entityEntry, originalValues, changeType, entityBagStateManager); } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs index 1172e15..ecf8bcc 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextFactory.cs @@ -1,37 +1,36 @@ using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public static class TriggerContextFactory + where TEntityType : class { - public static class TriggerContextFactory - where TEntityType : class - { - readonly static Func> _factoryMethod = CreateFactoryMethod(); + readonly static Func> _factoryMethod = CreateFactoryMethod(); - static Func> CreateFactoryMethod() - { - var entityEntryParamExpression = Expression.Parameter(typeof(EntityEntry), "entityEntry"); - var originalValuesParamExpression = Expression.Parameter(typeof(PropertyValues), "originalValues"); - var changeTypeParamExpression = Expression.Parameter(typeof(ChangeType), "changeType"); - var entityBagStateManagerExpression = Expression.Parameter(typeof(EntityBagStateManager), "entityBagStateManager"); + static Func> CreateFactoryMethod() + { + var entityEntryParamExpression = Expression.Parameter(typeof(EntityEntry), "entityEntry"); + var originalValuesParamExpression = Expression.Parameter(typeof(PropertyValues), "originalValues"); + var changeTypeParamExpression = Expression.Parameter(typeof(ChangeType), "changeType"); + var entityBagStateManagerExpression = Expression.Parameter(typeof(EntityBagStateManager), "entityBagStateManager"); - return Expression.Lambda>>( - Expression.New( - typeof(TriggerContext<>).MakeGenericType(typeof(TEntityType)).GetConstructor([typeof(EntityEntry), typeof(PropertyValues), typeof(ChangeType), typeof(EntityBagStateManager)])!, - entityEntryParamExpression, - originalValuesParamExpression, - changeTypeParamExpression, - entityBagStateManagerExpression - ), + return Expression.Lambda>>( + Expression.New( + typeof(TriggerContext<>).MakeGenericType(typeof(TEntityType)).GetConstructor([typeof(EntityEntry), typeof(PropertyValues), typeof(ChangeType), typeof(EntityBagStateManager)])!, entityEntryParamExpression, originalValuesParamExpression, changeTypeParamExpression, entityBagStateManagerExpression - ) - .Compile(); - } - - public static object Activate(EntityEntry entityEntry, PropertyValues? originalValues, ChangeType changeType, EntityBagStateManager entityBagStateManager) - => _factoryMethod(entityEntry, originalValues, changeType, entityBagStateManager); + ), + entityEntryParamExpression, + originalValuesParamExpression, + changeTypeParamExpression, + entityBagStateManagerExpression + ) + .Compile(); } + + public static object Activate(EntityEntry entityEntry, PropertyValues? originalValues, ChangeType changeType, EntityBagStateManager entityBagStateManager) + => _factoryMethod(entityEntry, originalValues, changeType, entityBagStateManager); } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs index d5f59d7..ce763a2 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerContextTracker.cs @@ -2,135 +2,134 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public sealed class TriggerContextTracker(ChangeTracker changeTracker, ICascadeStrategy cascadingStrategy) { - public sealed class TriggerContextTracker(ChangeTracker changeTracker, ICascadeStrategy cascadingStrategy) - { - readonly ChangeTracker _changeTracker = changeTracker; - readonly ICascadeStrategy _cascadingStrategy = cascadingStrategy; + readonly ChangeTracker _changeTracker = changeTracker; + readonly ICascadeStrategy _cascadingStrategy = cascadingStrategy; - List? _discoveredChanges; - List? _capturedChangeIndexes; + List? _discoveredChanges; + List? _capturedChangeIndexes; - static ChangeType? ResolveChangeType(EntityEntry entry) => entry.State switch { - EntityState.Added => ChangeType.Added, - EntityState.Modified => ChangeType.Modified, - EntityState.Deleted => ChangeType.Deleted, - _ => null, - }; + static ChangeType? ResolveChangeType(EntityEntry entry) => entry.State switch { + EntityState.Added => ChangeType.Added, + EntityState.Modified => ChangeType.Modified, + EntityState.Deleted => ChangeType.Deleted, + _ => null, + }; - public IEnumerable? DiscoveredChanges + public IEnumerable? DiscoveredChanges + { + get { - get + if (_discoveredChanges == null) + { + return null; + } + else { - if (_discoveredChanges == null) + if (_capturedChangeIndexes == null) { - return null; + return _discoveredChanges; } else { - if (_capturedChangeIndexes == null) - { - return _discoveredChanges; - } - else - { - return _discoveredChanges.Where((_, index) => !_capturedChangeIndexes.Contains(index)); - } + return _discoveredChanges.Where((_, index) => !_capturedChangeIndexes.Contains(index)); } } } + } - public IEnumerable DiscoverChanges() - { - int startIndex; + public IEnumerable DiscoverChanges() + { + int startIndex; - _changeTracker.DetectChanges(); - var entries = _changeTracker.Entries(); + _changeTracker.DetectChanges(); + var entries = _changeTracker.Entries(); - if (_discoveredChanges == null) - { - _discoveredChanges = new List(entries.Count()); - startIndex = 0; - } - else - { - startIndex = _discoveredChanges.Count; - } + if (_discoveredChanges == null) + { + _discoveredChanges = new List(entries.Count()); + startIndex = 0; + } + else + { + startIndex = _discoveredChanges.Count; + } - foreach (var entry in entries) + foreach (var entry in entries) + { + var changeType = ResolveChangeType(entry); + if (changeType != null) { - var changeType = ResolveChangeType(entry); - if (changeType != null) + if (startIndex > 0) { - if (startIndex > 0) - { - var canCascade = true; + var canCascade = true; - foreach (var discoveredChange in _discoveredChanges) + foreach (var discoveredChange in _discoveredChanges) + { + if (discoveredChange.Entity == entry.Entity) { - if (discoveredChange.Entity == entry.Entity) - { - canCascade = _cascadingStrategy.CanCascade(entry, changeType.Value, discoveredChange); + canCascade = _cascadingStrategy.CanCascade(entry, changeType.Value, discoveredChange); - if (!canCascade) - { - break; - } + if (!canCascade) + { + break; } } + } - if (!canCascade) - { - continue; - } + if (!canCascade) + { + continue; } + } - var triggerContextDescriptor = new TriggerContextDescriptor(entry, changeType.Value); + var triggerContextDescriptor = new TriggerContextDescriptor(entry, changeType.Value); - _discoveredChanges.Add(triggerContextDescriptor!); - } + _discoveredChanges.Add(triggerContextDescriptor!); } + } - if (startIndex == 0) - { - return _discoveredChanges; - } - else - { - return _discoveredChanges.Skip(startIndex); - } + if (startIndex == 0) + { + return _discoveredChanges; + } + else + { + return _discoveredChanges.Skip(startIndex); } + } - public void CaptureChanges() + public void CaptureChanges() + { + if (_discoveredChanges != null) { - if (_discoveredChanges != null) + var changesCount = _discoveredChanges.Count; + if (changesCount > 0) { - var changesCount = _discoveredChanges.Count; - if (changesCount > 0) - { - _capturedChangeIndexes ??= new List(changesCount); // assuming all will be captured + _capturedChangeIndexes ??= new List(changesCount); // assuming all will be captured - for (var changeIndex = 0; changeIndex < changesCount; changeIndex++) + for (var changeIndex = 0; changeIndex < changesCount; changeIndex++) + { + if (!_capturedChangeIndexes.Contains(changeIndex)) { - if (!_capturedChangeIndexes.Contains(changeIndex)) - { - var discoveredChange = _discoveredChanges[changeIndex]; + var discoveredChange = _discoveredChanges[changeIndex]; - var currentEntityEntry = _changeTracker.Context.Entry(discoveredChange.Entity); - var changeType = ResolveChangeType(currentEntityEntry); + var currentEntityEntry = _changeTracker.Context.Entry(discoveredChange.Entity); + var changeType = ResolveChangeType(currentEntityEntry); - if (changeType != discoveredChange.ChangeType) - { - _capturedChangeIndexes.Add(changeIndex); - } + if (changeType != discoveredChange.ChangeType) + { + _capturedChangeIndexes.Add(changeIndex); } } } } } - - public void UncaptureChanges() - => _capturedChangeIndexes = null; } + + public void UncaptureChanges() + => _capturedChangeIndexes = null; } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptor.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptor.cs index 93b3963..52a0020 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptor.cs @@ -1,34 +1,33 @@ using EntityFrameworkCore.Triggered.Internal.Descriptors; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public class TriggerDescriptor { - public class TriggerDescriptor + readonly ITriggerTypeDescriptor _triggerTypeDescriptor; + readonly object _trigger; + readonly int _priority; + + public TriggerDescriptor(ITriggerTypeDescriptor triggerTypeDescriptor, object trigger) { - readonly ITriggerTypeDescriptor _triggerTypeDescriptor; - readonly object _trigger; - readonly int _priority; + _triggerTypeDescriptor = triggerTypeDescriptor ?? throw new ArgumentNullException(nameof(triggerTypeDescriptor)); + _trigger = trigger ?? throw new ArgumentNullException(nameof(trigger)); - public TriggerDescriptor(ITriggerTypeDescriptor triggerTypeDescriptor, object trigger) + if (_trigger is ITriggerPriority triggerPriority) { - _triggerTypeDescriptor = triggerTypeDescriptor ?? throw new ArgumentNullException(nameof(triggerTypeDescriptor)); - _trigger = trigger ?? throw new ArgumentNullException(nameof(trigger)); - - if (_trigger is ITriggerPriority triggerPriority) - { - _priority = triggerPriority.Priority; - } - else - { - _priority = 0; - } + _priority = triggerPriority.Priority; } + else + { + _priority = 0; + } + } - public ITriggerTypeDescriptor TypeDescriptor => _triggerTypeDescriptor; - public object Trigger => _trigger; - public int Priority => _priority; + public ITriggerTypeDescriptor TypeDescriptor => _triggerTypeDescriptor; + public object Trigger => _trigger; + public int Priority => _priority; - public void Invoke(object triggerContext, Exception? exception) - => _triggerTypeDescriptor.Invoke(_trigger, triggerContext, exception); + public void Invoke(object triggerContext, Exception? exception) + => _triggerTypeDescriptor.Invoke(_trigger, triggerContext, exception); - } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs index e6c4cc8..908f5f9 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptorComparer.cs @@ -1,24 +1,23 @@ -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public sealed class TriggerDescriptorComparer : IComparer, IComparer { - public sealed class TriggerDescriptorComparer : IComparer, IComparer + public int Compare(TriggerDescriptor? x, TriggerDescriptor? y) { - public int Compare(TriggerDescriptor? x, TriggerDescriptor? y) - { - ArgumentNullException.ThrowIfNull(x); + ArgumentNullException.ThrowIfNull(x); - ArgumentNullException.ThrowIfNull(y); + ArgumentNullException.ThrowIfNull(y); - return x.Priority - y.Priority; - } + return x.Priority - y.Priority; + } - public int Compare(AsyncTriggerDescriptor? x, AsyncTriggerDescriptor? y) - { - ArgumentNullException.ThrowIfNull(x); + public int Compare(AsyncTriggerDescriptor? x, AsyncTriggerDescriptor? y) + { + ArgumentNullException.ThrowIfNull(x); - ArgumentNullException.ThrowIfNull(y); + ArgumentNullException.ThrowIfNull(y); - return x.Priority - y.Priority; - } + return x.Priority - y.Priority; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs index 206e2d6..b011b66 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerDiscoveryService.cs @@ -1,129 +1,128 @@ using EntityFrameworkCore.Triggered.Internal.Descriptors; using Microsoft.EntityFrameworkCore.Infrastructure; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public sealed class TriggerDiscoveryService(ITriggerServiceProviderAccessor triggerServiceProviderAccessor, ITriggerTypeRegistryService triggerTypeRegistryService, TriggerFactory triggerFactory) : ITriggerDiscoveryService, IResettableService { - public sealed class TriggerDiscoveryService(ITriggerServiceProviderAccessor triggerServiceProviderAccessor, ITriggerTypeRegistryService triggerTypeRegistryService, TriggerFactory triggerFactory) : ITriggerDiscoveryService, IResettableService - { - readonly static TriggerDescriptorComparer _triggerDescriptorComparer = new(); - readonly ITriggerServiceProviderAccessor _triggerServiceProviderAccessor = triggerServiceProviderAccessor; - readonly ITriggerTypeRegistryService _triggerTypeRegistryService = triggerTypeRegistryService ?? throw new ArgumentNullException(nameof(triggerTypeRegistryService)); - readonly TriggerFactory _triggerFactory = triggerFactory; + readonly static TriggerDescriptorComparer _triggerDescriptorComparer = new(); + readonly ITriggerServiceProviderAccessor _triggerServiceProviderAccessor = triggerServiceProviderAccessor; + readonly ITriggerTypeRegistryService _triggerTypeRegistryService = triggerTypeRegistryService ?? throw new ArgumentNullException(nameof(triggerTypeRegistryService)); + readonly TriggerFactory _triggerFactory = triggerFactory; - IServiceProvider? _serviceProvider; + IServiceProvider? _serviceProvider; + + public IEnumerable DiscoverTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) + { + var registry = _triggerTypeRegistryService.ResolveRegistry(openTriggerType, entityType, triggerTypeDescriptorFactory); - public IEnumerable DiscoverTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) + var triggerTypeDescriptors = registry.GetTriggerTypeDescriptors(); + if (triggerTypeDescriptors.Length == 0) { - var registry = _triggerTypeRegistryService.ResolveRegistry(openTriggerType, entityType, triggerTypeDescriptorFactory); + return []; + } + else + { + List? triggerDescriptors = null; - var triggerTypeDescriptors = registry.GetTriggerTypeDescriptors(); - if (triggerTypeDescriptors.Length == 0) - { - return []; - } - else + foreach (var triggerTypeDescriptor in triggerTypeDescriptors) { - List? triggerDescriptors = null; - - foreach (var triggerTypeDescriptor in triggerTypeDescriptors) + var triggers = _triggerFactory.Resolve(ServiceProvider, triggerTypeDescriptor.TriggerType); + foreach (var trigger in triggers) { - var triggers = _triggerFactory.Resolve(ServiceProvider, triggerTypeDescriptor.TriggerType); - foreach (var trigger in triggers) - { - triggerDescriptors ??= []; + triggerDescriptors ??= []; - if (trigger != null) - { - triggerDescriptors.Add(new TriggerDescriptor(triggerTypeDescriptor, trigger)); - } + if (trigger != null) + { + triggerDescriptors.Add(new TriggerDescriptor(triggerTypeDescriptor, trigger)); } } - - if (triggerDescriptors == null) - { - return []; - } - else - { - triggerDescriptors.Sort(_triggerDescriptorComparer); - return triggerDescriptors; - } } - } - - public IEnumerable DiscoverAsyncTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) - { - var registry = _triggerTypeRegistryService.ResolveRegistry(openTriggerType, entityType, triggerTypeDescriptorFactory); - var triggerTypeDescriptors = registry.GetTriggerTypeDescriptors(); - if (triggerTypeDescriptors.Length == 0) + if (triggerDescriptors == null) { return []; } else { - List? triggerDescriptors = null; + triggerDescriptors.Sort(_triggerDescriptorComparer); + return triggerDescriptors; + } + } + } - foreach (var triggerTypeDescriptor in triggerTypeDescriptors) + public IEnumerable DiscoverAsyncTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) + { + var registry = _triggerTypeRegistryService.ResolveRegistry(openTriggerType, entityType, triggerTypeDescriptorFactory); + + var triggerTypeDescriptors = registry.GetTriggerTypeDescriptors(); + if (triggerTypeDescriptors.Length == 0) + { + return []; + } + else + { + List? triggerDescriptors = null; + + foreach (var triggerTypeDescriptor in triggerTypeDescriptors) + { + var triggers = _triggerFactory.Resolve(ServiceProvider, triggerTypeDescriptor.TriggerType); + foreach (var trigger in triggers) { - var triggers = _triggerFactory.Resolve(ServiceProvider, triggerTypeDescriptor.TriggerType); - foreach (var trigger in triggers) - { - triggerDescriptors ??= []; + triggerDescriptors ??= []; - if (trigger != null) - { - triggerDescriptors.Add(new AsyncTriggerDescriptor(triggerTypeDescriptor, trigger)); - } + if (trigger != null) + { + triggerDescriptors.Add(new AsyncTriggerDescriptor(triggerTypeDescriptor, trigger)); } } + } - if (triggerDescriptors == null) - { - return []; - } - else - { - triggerDescriptors.Sort(_triggerDescriptorComparer); - return triggerDescriptors; - } + if (triggerDescriptors == null) + { + return []; + } + else + { + triggerDescriptors.Sort(_triggerDescriptorComparer); + return triggerDescriptors; } } + } - public IEnumerable DiscoverTriggers() - { - // We can skip the registry as there is no generic argument - var triggers = _triggerFactory.Resolve(ServiceProvider, typeof(TTrigger)); - - return triggers - .Select((trigger, index) => ( - trigger, - defaultPriority: index, - customPriority: (trigger as ITriggerPriority)?.Priority ?? 0 - )) - .OrderBy(x => x.customPriority) - .ThenBy(x => x.defaultPriority) - .Select(x => x.trigger) - .Cast(); - } + public IEnumerable DiscoverTriggers() + { + // We can skip the registry as there is no generic argument + var triggers = _triggerFactory.Resolve(ServiceProvider, typeof(TTrigger)); + + return triggers + .Select((trigger, index) => ( + trigger, + defaultPriority: index, + customPriority: (trigger as ITriggerPriority)?.Priority ?? 0 + )) + .OrderBy(x => x.customPriority) + .ThenBy(x => x.defaultPriority) + .Select(x => x.trigger) + .Cast(); + } - public IServiceProvider ServiceProvider + public IServiceProvider ServiceProvider + { + get { - get - { - _serviceProvider ??= _triggerServiceProviderAccessor.GetTriggerServiceProvider(); + _serviceProvider ??= _triggerServiceProviderAccessor.GetTriggerServiceProvider(); - return _serviceProvider; - } - set => _serviceProvider = value; + return _serviceProvider; } + set => _serviceProvider = value; + } - public void ResetState() => _serviceProvider = null; + public void ResetState() => _serviceProvider = null; - public Task ResetStateAsync(CancellationToken cancellationToken = default) - { - ResetState(); - return Task.CompletedTask; - } + public Task ResetStateAsync(CancellationToken cancellationToken = default) + { + ResetState(); + return Task.CompletedTask; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs index 278c5e0..5079fe8 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerFactory.cs @@ -1,42 +1,41 @@ using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public sealed class TriggerFactory(IServiceProvider internalServiceProvider) { - public sealed class TriggerFactory(IServiceProvider internalServiceProvider) - { - readonly static ConcurrentDictionary _instanceFactoryTypeCache = new(); - readonly IServiceProvider _internalServiceProvider = internalServiceProvider; + readonly static ConcurrentDictionary _instanceFactoryTypeCache = new(); + readonly IServiceProvider _internalServiceProvider = internalServiceProvider; - public IEnumerable Resolve(IServiceProvider serviceProvider, Type triggerType) + public IEnumerable Resolve(IServiceProvider serviceProvider, Type triggerType) + { + // triggers may be directly registered with our DI container + if (serviceProvider is not null) { - // triggers may be directly registered with our DI container - if (serviceProvider is not null) + var triggers = serviceProvider.GetServices(triggerType); + foreach (var trigger in triggers) { - var triggers = serviceProvider.GetServices(triggerType); - foreach (var trigger in triggers) + if (trigger is not null) { - if (trigger is not null) - { - yield return trigger; - } + yield return trigger; } } + } - // Alternatively, triggers may be registered with the extension configuration - var instanceFactoryType = _instanceFactoryTypeCache.GetOrAdd(triggerType, - triggerType => typeof(ITriggerInstanceFactory<>).MakeGenericType(triggerType) - ); + // Alternatively, triggers may be registered with the extension configuration + var instanceFactoryType = _instanceFactoryTypeCache.GetOrAdd(triggerType, + triggerType => typeof(ITriggerInstanceFactory<>).MakeGenericType(triggerType) + ); - var triggerServiceFactories = _internalServiceProvider.GetServices(instanceFactoryType); - if (triggerServiceFactories.Any()) + var triggerServiceFactories = _internalServiceProvider.GetServices(instanceFactoryType); + if (triggerServiceFactories.Any()) + { + foreach (var triggerServiceFactory in triggerServiceFactories) { - foreach (var triggerServiceFactory in triggerServiceFactories) + if (triggerServiceFactory is not null) { - if (triggerServiceFactory is not null) - { - yield return ((ITriggerInstanceFactory)triggerServiceFactory).Create(serviceProvider ?? _internalServiceProvider); - } + yield return ((ITriggerInstanceFactory)triggerServiceFactory).Create(serviceProvider ?? _internalServiceProvider); } } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs index c3da71d..06d1d44 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerInstanceFactory.cs @@ -1,44 +1,43 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; -namespace EntityFrameworkCore.Triggered.Internal -{ - - public interface ITriggerInstanceFactory - { - object Create(IServiceProvider serviceProvider); - } +namespace EntityFrameworkCore.Triggered.Internal; - public interface ITriggerInstanceFactory : ITriggerInstanceFactory, IResettableService - { - } +public interface ITriggerInstanceFactory +{ + object Create(IServiceProvider serviceProvider); +} - public sealed class TriggerInstanceFactory(object? instance) : ITriggerInstanceFactory - { - static ObjectFactory? _internalFactory; +public interface ITriggerInstanceFactory : ITriggerInstanceFactory, IResettableService +{ - object? _instance = instance; +} - public object Create(IServiceProvider serviceProvider) - { - if (_instance is not null) - { - return _instance; - } +public sealed class TriggerInstanceFactory(object? instance) : ITriggerInstanceFactory +{ + static ObjectFactory? _internalFactory; - _internalFactory ??= ActivatorUtilities.CreateFactory(typeof(TTriggerType), []); + object? _instance = instance; - _instance = _internalFactory(serviceProvider, null); + public object Create(IServiceProvider serviceProvider) + { + if (_instance is not null) + { return _instance; } - public void ResetState() => _instance = null; + _internalFactory ??= ActivatorUtilities.CreateFactory(typeof(TTriggerType), []); - public Task ResetStateAsync(CancellationToken cancellationToken = default) - { - ResetState(); - return Task.CompletedTask; - } + _instance = _internalFactory(serviceProvider, null); + return _instance; + } + + public void ResetState() => _instance = null; + + public Task ResetStateAsync(CancellationToken cancellationToken = default) + { + ResetState(); + return Task.CompletedTask; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs index 4a8afea..9b54e2e 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerSessionSaveChangesInterceptor.cs @@ -3,194 +3,194 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; -namespace EntityFrameworkCore.Triggered.Internal -{ +namespace EntityFrameworkCore.Triggered.Internal; + #pragma warning disable CS0618 // Type or member is obsolete (TriggeredDbContext with EFCore5) - public class TriggerSessionSaveChangesInterceptor : ISaveChangesInterceptor - { +public class TriggerSessionSaveChangesInterceptor : ISaveChangesInterceptor +{ #if DEBUG - DbContext? _capturedDbContext; + DbContext? _capturedDbContext; #endif - ITriggerSession? _triggerSession; - int _parallelSaveChangesCount; + ITriggerSession? _triggerSession; + int _parallelSaveChangesCount; - private void EnlistTriggerSession(DbContextEventData eventData) - { + private void EnlistTriggerSession(DbContextEventData eventData) + { #if DEBUG - if (_triggerSession != null) + if (_triggerSession != null) + { + Debug.Assert(_capturedDbContext == eventData.Context); + } + else + { + _capturedDbContext = eventData.Context; + } +#endif + + if (_triggerSession == null) + { + if (eventData.Context is null) { - Debug.Assert(_capturedDbContext == eventData.Context); + throw new InvalidOperationException("Expected a context"); } - else + + var triggerService = eventData.Context.GetService() ?? throw new InvalidOperationException("Triggers are not configured"); + + if (triggerService.Current != null) { - _capturedDbContext = eventData.Context; + _triggerSession = triggerService.Current; } -#endif - - if (_triggerSession == null) + else { - if (eventData.Context is null) - { - throw new InvalidOperationException("Expected a context"); - } - - var triggerService = eventData.Context.GetService() ?? throw new InvalidOperationException("Triggers are not configured"); - - if (triggerService.Current != null) - { - _triggerSession = triggerService.Current; - } - else - { - _triggerSession = triggerService.CreateSession(eventData.Context); - } + _triggerSession = triggerService.CreateSession(eventData.Context); } - - _parallelSaveChangesCount += 1; } - private void DelistTriggerSession(DbContextEventData eventData) - { - Debug.Assert(_triggerSession != null); + _parallelSaveChangesCount += 1; + } + + private void DelistTriggerSession(DbContextEventData eventData) + { + Debug.Assert(_triggerSession != null); #if DEBUG - Debug.Assert(_capturedDbContext == eventData.Context); + Debug.Assert(_capturedDbContext == eventData.Context); #endif - _parallelSaveChangesCount -= 1; + _parallelSaveChangesCount -= 1; - if (_parallelSaveChangesCount == 0) - { - _triggerSession.Dispose(); - _triggerSession = null; - } + if (_parallelSaveChangesCount == 0) + { + _triggerSession.Dispose(); + _triggerSession = null; } + } - public InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) - { - EnlistTriggerSession(eventData); - Debug.Assert(_triggerSession != null); - - var defaultAutoDetectChangesEnabled = eventData.Context!.ChangeTracker.AutoDetectChangesEnabled; + public InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) + { + EnlistTriggerSession(eventData); + Debug.Assert(_triggerSession != null); - try - { - eventData.Context.ChangeTracker.AutoDetectChangesEnabled = false; + var defaultAutoDetectChangesEnabled = eventData.Context!.ChangeTracker.AutoDetectChangesEnabled; - _triggerSession.RaiseBeforeSaveStartingTriggers(); - _triggerSession.RaiseBeforeSaveTriggers(); - _triggerSession.CaptureDiscoveredChanges(); - _triggerSession.RaiseBeforeSaveCompletedTriggers(); - } - catch - { - // We're aborting the SaveChanges call, delist the trigger session now - DelistTriggerSession(eventData); - throw; - } - finally - { - eventData.Context.ChangeTracker.AutoDetectChangesEnabled = defaultAutoDetectChangesEnabled; - } + try + { + eventData.Context.ChangeTracker.AutoDetectChangesEnabled = false; - return result; + _triggerSession.RaiseBeforeSaveStartingTriggers(); + _triggerSession.RaiseBeforeSaveTriggers(); + _triggerSession.CaptureDiscoveredChanges(); + _triggerSession.RaiseBeforeSaveCompletedTriggers(); } - - public async ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + catch + { + // We're aborting the SaveChanges call, delist the trigger session now + DelistTriggerSession(eventData); + throw; + } + finally { - EnlistTriggerSession(eventData); - Debug.Assert(_triggerSession != null); + eventData.Context.ChangeTracker.AutoDetectChangesEnabled = defaultAutoDetectChangesEnabled; + } - var defaultAutoDetectChangesEnabled = eventData.Context!.ChangeTracker.AutoDetectChangesEnabled; + return result; + } - try - { - eventData.Context.ChangeTracker.AutoDetectChangesEnabled = false; + public async ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + EnlistTriggerSession(eventData); + Debug.Assert(_triggerSession != null); - _triggerSession.RaiseBeforeSaveStartingTriggers(); - await _triggerSession.RaiseBeforeSaveStartingAsyncTriggers(cancellationToken).ConfigureAwait(false); + var defaultAutoDetectChangesEnabled = eventData.Context!.ChangeTracker.AutoDetectChangesEnabled; - _triggerSession.RaiseBeforeSaveTriggers(); - await _triggerSession.RaiseBeforeSaveAsyncTriggers(cancellationToken).ConfigureAwait(false); + try + { + eventData.Context.ChangeTracker.AutoDetectChangesEnabled = false; - _triggerSession.CaptureDiscoveredChanges(); + _triggerSession.RaiseBeforeSaveStartingTriggers(); + await _triggerSession.RaiseBeforeSaveStartingAsyncTriggers(cancellationToken).ConfigureAwait(false); - _triggerSession.RaiseBeforeSaveCompletedTriggers(); - await _triggerSession.RaiseBeforeSaveCompletedAsyncTriggers(cancellationToken).ConfigureAwait(false); - } - catch - { - // We're aborting the SaveChanges call, delist the trigger session now - DelistTriggerSession(eventData); - throw; - } - finally - { - eventData.Context.ChangeTracker.AutoDetectChangesEnabled = defaultAutoDetectChangesEnabled; - } + _triggerSession.RaiseBeforeSaveTriggers(); + await _triggerSession.RaiseBeforeSaveAsyncTriggers(cancellationToken).ConfigureAwait(false); - return result; - } + _triggerSession.CaptureDiscoveredChanges(); - public int SavedChanges(SaveChangesCompletedEventData eventData, int result) + _triggerSession.RaiseBeforeSaveCompletedTriggers(); + await _triggerSession.RaiseBeforeSaveCompletedAsyncTriggers(cancellationToken).ConfigureAwait(false); + } + catch + { + // We're aborting the SaveChanges call, delist the trigger session now + DelistTriggerSession(eventData); + throw; + } + finally { - Debug.Assert(_triggerSession != null); + eventData.Context.ChangeTracker.AutoDetectChangesEnabled = defaultAutoDetectChangesEnabled; + } - _triggerSession.RaiseAfterSaveStartingTriggers(); - _triggerSession.RaiseAfterSaveTriggers(); - _triggerSession.RaiseAfterSaveCompletedTriggers(); + return result; + } - DelistTriggerSession(eventData); + public int SavedChanges(SaveChangesCompletedEventData eventData, int result) + { + Debug.Assert(_triggerSession != null); - return result; - } + _triggerSession.RaiseAfterSaveStartingTriggers(); + _triggerSession.RaiseAfterSaveTriggers(); + _triggerSession.RaiseAfterSaveCompletedTriggers(); - public async ValueTask SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default) - { - Debug.Assert(_triggerSession != null); + DelistTriggerSession(eventData); - _triggerSession.RaiseAfterSaveStartingTriggers(); - await _triggerSession.RaiseAfterSaveStartingAsyncTriggers(cancellationToken).ConfigureAwait(false); + return result; + } - _triggerSession.RaiseAfterSaveTriggers(); - await _triggerSession.RaiseAfterSaveAsyncTriggers(cancellationToken).ConfigureAwait(false); + public async ValueTask SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default) + { + Debug.Assert(_triggerSession != null); - _triggerSession.RaiseAfterSaveCompletedTriggers(); - await _triggerSession.RaiseAfterSaveCompletedAsyncTriggers(cancellationToken).ConfigureAwait(false); + _triggerSession.RaiseAfterSaveStartingTriggers(); + await _triggerSession.RaiseAfterSaveStartingAsyncTriggers(cancellationToken).ConfigureAwait(false); - DelistTriggerSession(eventData); + _triggerSession.RaiseAfterSaveTriggers(); + await _triggerSession.RaiseAfterSaveAsyncTriggers(cancellationToken).ConfigureAwait(false); - return result; - } + _triggerSession.RaiseAfterSaveCompletedTriggers(); + await _triggerSession.RaiseAfterSaveCompletedAsyncTriggers(cancellationToken).ConfigureAwait(false); - public void SaveChangesFailed(DbContextErrorEventData eventData) - { - Debug.Assert(_triggerSession != null); + DelistTriggerSession(eventData); - _triggerSession.RaiseAfterSaveFailedStartingTriggers(eventData.Exception); - _triggerSession.RaiseAfterSaveFailedTriggers(eventData.Exception); - _triggerSession.RaiseAfterSaveFailedCompletedTriggers(eventData.Exception); + return result; + } - DelistTriggerSession(eventData); - } + public void SaveChangesFailed(DbContextErrorEventData eventData) + { + Debug.Assert(_triggerSession != null); - public async Task SaveChangesFailedAsync(DbContextErrorEventData eventData, CancellationToken cancellationToken = default) - { - Debug.Assert(_triggerSession != null); + _triggerSession.RaiseAfterSaveFailedStartingTriggers(eventData.Exception); + _triggerSession.RaiseAfterSaveFailedTriggers(eventData.Exception); + _triggerSession.RaiseAfterSaveFailedCompletedTriggers(eventData.Exception); - _triggerSession.RaiseAfterSaveFailedStartingTriggers(eventData.Exception); - await _triggerSession.RaiseAfterSaveFailedStartingAsyncTriggers(eventData.Exception, cancellationToken).ConfigureAwait(false); + DelistTriggerSession(eventData); + } - _triggerSession.RaiseAfterSaveFailedTriggers(eventData.Exception); - await _triggerSession.RaiseAfterSaveFailedAsyncTriggers(eventData.Exception, cancellationToken).ConfigureAwait(false); + public async Task SaveChangesFailedAsync(DbContextErrorEventData eventData, CancellationToken cancellationToken = default) + { + Debug.Assert(_triggerSession != null); - _triggerSession.RaiseAfterSaveFailedCompletedTriggers(eventData.Exception); - await _triggerSession.RaiseAfterSaveFailedCompletedAsyncTriggers(eventData.Exception, cancellationToken).ConfigureAwait(false); + _triggerSession.RaiseAfterSaveFailedStartingTriggers(eventData.Exception); + await _triggerSession.RaiseAfterSaveFailedStartingAsyncTriggers(eventData.Exception, cancellationToken).ConfigureAwait(false); - DelistTriggerSession(eventData); - } + _triggerSession.RaiseAfterSaveFailedTriggers(eventData.Exception); + await _triggerSession.RaiseAfterSaveFailedAsyncTriggers(eventData.Exception, cancellationToken).ConfigureAwait(false); + + _triggerSession.RaiseAfterSaveFailedCompletedTriggers(eventData.Exception); + await _triggerSession.RaiseAfterSaveFailedCompletedAsyncTriggers(eventData.Exception, cancellationToken).ConfigureAwait(false); + + DelistTriggerSession(eventData); } -#pragma warning restore CS0618 // Type or member is obsolete } +#pragma warning restore CS0618 // Type or member is obsolete + diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs index d99975e..cb75cc3 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeDescriptorHelpers.cs @@ -1,84 +1,83 @@ using System.Reflection; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +// Credits: https://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates/ +public static class TriggerTypeDescriptorHelpers { - // Credits: https://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates/ - public static class TriggerTypeDescriptorHelpers + public static Action GetWeakDelegate(Type triggerType, Type entityType, MethodInfo method) { - public static Action GetWeakDelegate(Type triggerType, Type entityType, MethodInfo method) - { - var triggerContextType = typeof(ITriggerContext<>).MakeGenericType(entityType); + var triggerContextType = typeof(ITriggerContext<>).MakeGenericType(entityType); - var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetWeakDelegateHelper), BindingFlags.Static | BindingFlags.NonPublic); - var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); + var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetWeakDelegateHelper), BindingFlags.Static | BindingFlags.NonPublic); + var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); - return (Action)constructedHelper.Invoke(null, [method])!; - } + return (Action)constructedHelper.Invoke(null, [method])!; + } - public static Action GetWeakDelegateWithException(Type triggerType, Type entityType, MethodInfo method) - { - var triggerContextType = typeof(ITriggerContext<>).MakeGenericType(entityType); + public static Action GetWeakDelegateWithException(Type triggerType, Type entityType, MethodInfo method) + { + var triggerContextType = typeof(ITriggerContext<>).MakeGenericType(entityType); - var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetWeakDelegateHelperWithException), BindingFlags.Static | BindingFlags.NonPublic); - var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); + var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetWeakDelegateHelperWithException), BindingFlags.Static | BindingFlags.NonPublic); + var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); - return (Action)constructedHelper.Invoke(null, [method])!; - } + return (Action)constructedHelper.Invoke(null, [method])!; + } - static Action GetWeakDelegateHelper(MethodInfo method) - where TTriggerType : class - { - var invocationDelegate = (Action)Delegate.CreateDelegate(typeof(Action), method); + static Action GetWeakDelegateHelper(MethodInfo method) + where TTriggerType : class + { + var invocationDelegate = (Action)Delegate.CreateDelegate(typeof(Action), method); - Action result = (object trigger, object triggerContext) => invocationDelegate((TTriggerType)trigger, (TTriggerContext)triggerContext); - return result; - } + Action result = (object trigger, object triggerContext) => invocationDelegate((TTriggerType)trigger, (TTriggerContext)triggerContext); + return result; + } - static Action GetWeakDelegateHelperWithException(MethodInfo method) - where TTriggerType : class - { - var invocationDelegate = (Action)Delegate.CreateDelegate(typeof(Action), method); + static Action GetWeakDelegateHelperWithException(MethodInfo method) + where TTriggerType : class + { + var invocationDelegate = (Action)Delegate.CreateDelegate(typeof(Action), method); - Action result = (object trigger, object triggerContext, Exception? exception) => invocationDelegate((TTriggerType)trigger, (TTriggerContext)triggerContext, exception); - return result; - } + Action result = (object trigger, object triggerContext, Exception? exception) => invocationDelegate((TTriggerType)trigger, (TTriggerContext)triggerContext, exception); + return result; + } - public static Func GetAsyncWeakDelegate(Type triggerType, Type entityType, MethodInfo method) - { - var triggerContextType = typeof(ITriggerContext<>).MakeGenericType(entityType); + public static Func GetAsyncWeakDelegate(Type triggerType, Type entityType, MethodInfo method) + { + var triggerContextType = typeof(ITriggerContext<>).MakeGenericType(entityType); - var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetAsyncWeakDelegateHelper), BindingFlags.Static | BindingFlags.NonPublic); - var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); + var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetAsyncWeakDelegateHelper), BindingFlags.Static | BindingFlags.NonPublic); + var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); - return (Func)constructedHelper.Invoke(null, [method])!; - } + return (Func)constructedHelper.Invoke(null, [method])!; + } - public static Func GetAsyncWeakDelegateWithException(Type triggerType, Type entityType, MethodInfo method) - { - var triggerContextType = typeof(ITriggerContext<>).MakeGenericType(entityType); + public static Func GetAsyncWeakDelegateWithException(Type triggerType, Type entityType, MethodInfo method) + { + var triggerContextType = typeof(ITriggerContext<>).MakeGenericType(entityType); - var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetAsyncWeakDelegateHelperWithException), BindingFlags.Static | BindingFlags.NonPublic); - var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); + var genericHelper = typeof(TriggerTypeDescriptorHelpers).GetMethod(nameof(TriggerTypeDescriptorHelpers.GetAsyncWeakDelegateHelperWithException), BindingFlags.Static | BindingFlags.NonPublic); + var constructedHelper = genericHelper!.MakeGenericMethod(triggerType, triggerContextType); - return (Func)constructedHelper.Invoke(null, [method])!; - } + return (Func)constructedHelper.Invoke(null, [method])!; + } - static Func GetAsyncWeakDelegateHelper(MethodInfo method) - where TTriggerType : class - { - var invocationDelegate = (Func)Delegate.CreateDelegate(typeof(Func), method); + static Func GetAsyncWeakDelegateHelper(MethodInfo method) + where TTriggerType : class + { + var invocationDelegate = (Func)Delegate.CreateDelegate(typeof(Func), method); - Func result = (object trigger, object triggerContext, CancellationToken cancellationToken) => invocationDelegate((TTriggerType)trigger, (TTriggerContext)triggerContext, cancellationToken); - return result; - } + Func result = (object trigger, object triggerContext, CancellationToken cancellationToken) => invocationDelegate((TTriggerType)trigger, (TTriggerContext)triggerContext, cancellationToken); + return result; + } - static Func GetAsyncWeakDelegateHelperWithException(MethodInfo method) - where TTriggerType : class - { - var invocationDelegate = (Func)Delegate.CreateDelegate(typeof(Func), method); + static Func GetAsyncWeakDelegateHelperWithException(MethodInfo method) + where TTriggerType : class + { + var invocationDelegate = (Func)Delegate.CreateDelegate(typeof(Func), method); - Func result = (object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) => invocationDelegate((TTriggerType)trigger, (TTriggerContext)triggerContext, exception, cancellationToken); - return result; - } + Func result = (object trigger, object triggerContext, Exception? exception, CancellationToken cancellationToken) => invocationDelegate((TTriggerType)trigger, (TTriggerContext)triggerContext, exception, cancellationToken); + return result; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs index ee3d379..591dafd 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistry.cs @@ -1,46 +1,45 @@ using EntityFrameworkCore.Triggered.Infrastructure.Internal; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public sealed class TriggerTypeRegistry(Type entityType, Func triggerTypeDescriptorFactory) { - public sealed class TriggerTypeRegistry(Type entityType, Func triggerTypeDescriptorFactory) - { - readonly Type _entityType = entityType; - readonly Func _triggerTypeDescriptorFactory = triggerTypeDescriptorFactory; + readonly Type _entityType = entityType; + readonly Func _triggerTypeDescriptorFactory = triggerTypeDescriptorFactory; - TTriggerTypeDescriptor[]? _resolvedDescriptors; + TTriggerTypeDescriptor[]? _resolvedDescriptors; - IEnumerable GetEntityTypeHierarchy() + IEnumerable GetEntityTypeHierarchy() + { + // Enumerable of the type hierarchy from base to concrete + var typeHierarchy = TypeHelpers.EnumerateTypeHierarchy(_entityType).Reverse(); + foreach (var type in typeHierarchy) { - // Enumerable of the type hierarchy from base to concrete - var typeHierarchy = TypeHelpers.EnumerateTypeHierarchy(_entityType).Reverse(); - foreach (var type in typeHierarchy) + foreach (var interfaceType in type.GetInterfaces()) { - foreach (var interfaceType in type.GetInterfaces()) - { - yield return interfaceType; + yield return interfaceType; - } - - yield return type; } + + yield return type; } + } - public TTriggerTypeDescriptor[] GetTriggerTypeDescriptors() + public TTriggerTypeDescriptor[] GetTriggerTypeDescriptors() + { + if (_resolvedDescriptors == null) { - if (_resolvedDescriptors == null) - { - var result = new List(); - - foreach (var triggerType in GetEntityTypeHierarchy().Distinct()) - { - var descriptor = _triggerTypeDescriptorFactory(triggerType); - result.Add(descriptor); - } + var result = new List(); - _resolvedDescriptors = result.ToArray(); + foreach (var triggerType in GetEntityTypeHierarchy().Distinct()) + { + var descriptor = _triggerTypeDescriptorFactory(triggerType); + result.Add(descriptor); } - return _resolvedDescriptors; + _resolvedDescriptors = result.ToArray(); } + + return _resolvedDescriptors; } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs index 75d417e..c0329ad 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggerTypeRegistryService.cs @@ -1,25 +1,24 @@ using System.Collections.Concurrent; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public sealed class TriggerTypeRegistryService : ITriggerTypeRegistryService { - public sealed class TriggerTypeRegistryService : ITriggerTypeRegistryService - { - readonly ConcurrentDictionary<(Type, Type, Type), object> _resolvedRegistries = new(); + readonly ConcurrentDictionary<(Type, Type, Type), object> _resolvedRegistries = new(); - TriggerTypeRegistry CreateRegistry(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) - => (TriggerTypeRegistry)_resolvedRegistries.GetOrAdd((openTriggerType, entityType, typeof(TTriggerTypeDescriptor)), _ => new TriggerTypeRegistry(entityType, triggerTypeDescriptorFactory)); + TriggerTypeRegistry CreateRegistry(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) + => (TriggerTypeRegistry)_resolvedRegistries.GetOrAdd((openTriggerType, entityType, typeof(TTriggerTypeDescriptor)), _ => new TriggerTypeRegistry(entityType, triggerTypeDescriptorFactory)); - public TriggerTypeRegistry ResolveRegistry(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) + public TriggerTypeRegistry ResolveRegistry(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) + { + if (_resolvedRegistries.TryGetValue((openTriggerType, entityType, typeof(TTriggerTypeDescriptor)), out var registry)) + { + return (TriggerTypeRegistry)registry; + } + else { - if (_resolvedRegistries.TryGetValue((openTriggerType, entityType, typeof(TTriggerTypeDescriptor)), out var registry)) - { - return (TriggerTypeRegistry)registry; - } - else - { - // Use an extra method to prevent allocation of a DispayClass in this method - return CreateRegistry(openTriggerType, entityType, triggerTypeDescriptorFactory); - } + // Use an extra method to prevent allocation of a DispayClass in this method + return CreateRegistry(openTriggerType, entityType, triggerTypeDescriptorFactory); } } } diff --git a/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs b/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs index e1c77e5..656b75e 100644 --- a/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs +++ b/src/EntityFrameworkCore.Triggered/Internal/TriggeredDbContextFactory.cs @@ -2,46 +2,45 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -namespace EntityFrameworkCore.Triggered.Internal +namespace EntityFrameworkCore.Triggered.Internal; + +public sealed class TriggeredDbContextFactory(TFactory contextFactory, IServiceProvider serviceProvider) : IDbContextFactory + where TContext : DbContext + where TFactory : IDbContextFactory { - public sealed class TriggeredDbContextFactory(TFactory contextFactory, IServiceProvider serviceProvider) : IDbContextFactory - where TContext : DbContext - where TFactory : IDbContextFactory + private readonly TFactory _contextFactory = contextFactory; + private readonly IServiceProvider _serviceProvider = serviceProvider; + + public TContext CreateDbContext() { - private readonly TFactory _contextFactory = contextFactory; - private readonly IServiceProvider _serviceProvider = serviceProvider; + var context = _contextFactory.CreateDbContext(); + Debug.Assert(context != null); - public TContext CreateDbContext() + var applicationTriggerServiceProviderAccessor = context.GetService(); + if (applicationTriggerServiceProviderAccessor != null) { - var context = _contextFactory.CreateDbContext(); - Debug.Assert(context != null); - - var applicationTriggerServiceProviderAccessor = context.GetService(); - if (applicationTriggerServiceProviderAccessor != null) - { - applicationTriggerServiceProviderAccessor.SetTriggerServiceProvider(new HybridServiceProvider(_serviceProvider, context)); - } - - return context; + applicationTriggerServiceProviderAccessor.SetTriggerServiceProvider(new HybridServiceProvider(_serviceProvider, context)); } + + return context; } +} - public sealed class TriggeredDbContextFactory(Func> contextFactoryFactory, IServiceProvider serviceProvider) : IDbContextFactory - where TContext : DbContext - { - readonly Func> _contextFactoryFactory = contextFactoryFactory; - readonly IServiceProvider _serviceProvider = serviceProvider; +public sealed class TriggeredDbContextFactory(Func> contextFactoryFactory, IServiceProvider serviceProvider) : IDbContextFactory + where TContext : DbContext +{ + readonly Func> _contextFactoryFactory = contextFactoryFactory; + readonly IServiceProvider _serviceProvider = serviceProvider; - public TContext CreateDbContext() - { - var contextFactory = _contextFactoryFactory(_serviceProvider); - var context = contextFactory.CreateDbContext(); - Debug.Assert(context is not null); + public TContext CreateDbContext() + { + var contextFactory = _contextFactoryFactory(_serviceProvider); + var context = contextFactory.CreateDbContext(); + Debug.Assert(context is not null); - var applicationTriggerServiceProviderAccessor = context.GetService(); - applicationTriggerServiceProviderAccessor?.SetTriggerServiceProvider(new HybridServiceProvider(_serviceProvider, context)); + var applicationTriggerServiceProviderAccessor = context.GetService(); + applicationTriggerServiceProviderAccessor?.SetTriggerServiceProvider(new HybridServiceProvider(_serviceProvider, context)); - return context; - } + return context; } } diff --git a/src/EntityFrameworkCore.Triggered/TriggerContext.cs b/src/EntityFrameworkCore.Triggered/TriggerContext.cs index db706c8..4b000ea 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerContext.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerContext.cs @@ -1,42 +1,41 @@ using EntityFrameworkCore.Triggered.Internal; using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public class TriggerContext(EntityEntry entityEntry, PropertyValues? originalValues, ChangeType changeType, EntityBagStateManager entityBagStateManager) : ITriggerContext + where TEntity : class { - public class TriggerContext(EntityEntry entityEntry, PropertyValues? originalValues, ChangeType changeType, EntityBagStateManager entityBagStateManager) : ITriggerContext - where TEntity : class - { - readonly EntityEntry _entityEntry = entityEntry; - readonly ChangeType _type = changeType; - readonly PropertyValues? _originalValues = originalValues; - readonly EntityBagStateManager _entityBagStateManager = entityBagStateManager; + readonly EntityEntry _entityEntry = entityEntry; + readonly ChangeType _type = changeType; + readonly PropertyValues? _originalValues = originalValues; + readonly EntityBagStateManager _entityBagStateManager = entityBagStateManager; - TEntity? _unmodifiedEntity; + TEntity? _unmodifiedEntity; - public ChangeType ChangeType => _type; - public TEntity Entity => (TEntity)_entityEntry.Entity; - public TEntity? UnmodifiedEntity + public ChangeType ChangeType => _type; + public TEntity Entity => (TEntity)_entityEntry.Entity; + public TEntity? UnmodifiedEntity + { + get { - get + if (_type == ChangeType.Added) + { + return null; + } + else { - if (_type == ChangeType.Added) + if (_unmodifiedEntity == null && _originalValues != null) { - return null; + _unmodifiedEntity = (TEntity)_originalValues.ToObject(); } - else - { - if (_unmodifiedEntity == null && _originalValues != null) - { - _unmodifiedEntity = (TEntity)_originalValues.ToObject(); - } - return _unmodifiedEntity; - } + return _unmodifiedEntity; } } + } - public IDictionary Items => _entityBagStateManager.GetForEntity(_entityEntry.Entity); + public IDictionary Items => _entityBagStateManager.GetForEntity(_entityEntry.Entity); - public EntityEntry Entry => (EntityEntry)_entityEntry; - } + public EntityEntry Entry => (EntityEntry)_entityEntry; } diff --git a/src/EntityFrameworkCore.Triggered/TriggerOptions.cs b/src/EntityFrameworkCore.Triggered/TriggerOptions.cs index e72f259..f47d3f2 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerOptions.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerOptions.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public class TriggerOptions { - public class TriggerOptions - { - public int MaxCascadeCycles { get; set; } = 100; - } + public int MaxCascadeCycles { get; set; } = 100; } diff --git a/src/EntityFrameworkCore.Triggered/TriggerService.cs b/src/EntityFrameworkCore.Triggered/TriggerService.cs index 20bdf03..15696e4 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerService.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerService.cs @@ -5,73 +5,72 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public class TriggerService : ITriggerService, IResettableService { - public class TriggerService : ITriggerService, IResettableService - { - readonly ITriggerDiscoveryService _triggerDiscoveryService; - readonly ICascadeStrategy _cascadingStrategy; - readonly ILoggerFactory _loggerFactory; - readonly TriggerSessionConfiguration _defaultConfiguration; + readonly ITriggerDiscoveryService _triggerDiscoveryService; + readonly ICascadeStrategy _cascadingStrategy; + readonly ILoggerFactory _loggerFactory; + readonly TriggerSessionConfiguration _defaultConfiguration; - ITriggerSession? _currentTriggerSession; + ITriggerSession? _currentTriggerSession; - public TriggerService(ITriggerDiscoveryService triggerDiscoveryService, ICascadeStrategy cascadingStrategy, ILoggerFactory loggerFactory, IOptions triggerOptions) - { - _triggerDiscoveryService = triggerDiscoveryService ?? throw new ArgumentNullException(nameof(triggerDiscoveryService)); - _cascadingStrategy = cascadingStrategy ?? throw new ArgumentNullException(nameof(cascadingStrategy)); - _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); - _defaultConfiguration = new TriggerSessionConfiguration(false, triggerOptions.Value.MaxCascadeCycles); + public TriggerService(ITriggerDiscoveryService triggerDiscoveryService, ICascadeStrategy cascadingStrategy, ILoggerFactory loggerFactory, IOptions triggerOptions) + { + _triggerDiscoveryService = triggerDiscoveryService ?? throw new ArgumentNullException(nameof(triggerDiscoveryService)); + _cascadingStrategy = cascadingStrategy ?? throw new ArgumentNullException(nameof(cascadingStrategy)); + _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); + _defaultConfiguration = new TriggerSessionConfiguration(false, triggerOptions.Value.MaxCascadeCycles); - Configuration = _defaultConfiguration; - } + Configuration = _defaultConfiguration; + } - public ITriggerSession? Current - { - get => _currentTriggerSession; - set => _currentTriggerSession = value; - } + public ITriggerSession? Current + { + get => _currentTriggerSession; + set => _currentTriggerSession = value; + } - public TriggerSessionConfiguration Configuration { get; set; } + public TriggerSessionConfiguration Configuration { get; set; } - public ITriggerSession CreateSession(DbContext context, IServiceProvider? serviceProvider) - => CreateSession(context, Configuration, serviceProvider); + public ITriggerSession CreateSession(DbContext context, IServiceProvider? serviceProvider) + => CreateSession(context, Configuration, serviceProvider); - public ITriggerSession CreateSession(DbContext context, TriggerSessionConfiguration configuration, IServiceProvider? serviceProvider) - { - ArgumentNullException.ThrowIfNull(context); + public ITriggerSession CreateSession(DbContext context, TriggerSessionConfiguration configuration, IServiceProvider? serviceProvider) + { + ArgumentNullException.ThrowIfNull(context); - var triggerContextTracker = new TriggerContextTracker(context.ChangeTracker, _cascadingStrategy); + var triggerContextTracker = new TriggerContextTracker(context.ChangeTracker, _cascadingStrategy); - if (serviceProvider != null) - { - _triggerDiscoveryService.ServiceProvider = serviceProvider; - } + if (serviceProvider != null) + { + _triggerDiscoveryService.ServiceProvider = serviceProvider; + } - var triggerSession = new TriggerSession(this, configuration, _triggerDiscoveryService, triggerContextTracker, _loggerFactory.CreateLogger()); + var triggerSession = new TriggerSession(this, configuration, _triggerDiscoveryService, triggerContextTracker, _loggerFactory.CreateLogger()); - _currentTriggerSession = triggerSession; + _currentTriggerSession = triggerSession; - return triggerSession; - } + return triggerSession; + } - public void ResetState() + public void ResetState() + { + if (_currentTriggerSession != null) { - if (_currentTriggerSession != null) - { - _currentTriggerSession.Dispose(); - _currentTriggerSession = null; - } - - Configuration = _defaultConfiguration; + _currentTriggerSession.Dispose(); + _currentTriggerSession = null; } - public Task ResetStateAsync(CancellationToken cancellationToken = default) - { - ResetState(); + Configuration = _defaultConfiguration; + } - return Task.CompletedTask; - } + public Task ResetStateAsync(CancellationToken cancellationToken = default) + { + ResetState(); + + return Task.CompletedTask; } } diff --git a/src/EntityFrameworkCore.Triggered/TriggerSession.cs b/src/EntityFrameworkCore.Triggered/TriggerSession.cs index 402f95b..6e08eea 100644 --- a/src/EntityFrameworkCore.Triggered/TriggerSession.cs +++ b/src/EntityFrameworkCore.Triggered/TriggerSession.cs @@ -3,342 +3,341 @@ using EntityFrameworkCore.Triggered.Lifecycles; using Microsoft.Extensions.Logging; -namespace EntityFrameworkCore.Triggered +namespace EntityFrameworkCore.Triggered; + +public class TriggerSession(ITriggerService triggerService, TriggerSessionConfiguration configuration, ITriggerDiscoveryService triggerDiscoveryService, TriggerContextTracker tracker, ILogger logger) : ITriggerSession { - public class TriggerSession(ITriggerService triggerService, TriggerSessionConfiguration configuration, ITriggerDiscoveryService triggerDiscoveryService, TriggerContextTracker tracker, ILogger logger) : ITriggerSession - { - static ITriggerContextDiscoveryStrategy? _beforeSaveTriggerContextDiscoveryStrategy; - static ITriggerContextDiscoveryStrategy? _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges; // To satisfy RaiseBeforeSaveTrigger's overload - static ITriggerContextDiscoveryStrategy? _afterSaveTriggerContextDiscoveryStrategy; - static ITriggerContextDiscoveryStrategy? _afterSaveFailedTriggerContextDiscoveryStrategy; + static ITriggerContextDiscoveryStrategy? _beforeSaveTriggerContextDiscoveryStrategy; + static ITriggerContextDiscoveryStrategy? _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges; // To satisfy RaiseBeforeSaveTrigger's overload + static ITriggerContextDiscoveryStrategy? _afterSaveTriggerContextDiscoveryStrategy; + static ITriggerContextDiscoveryStrategy? _afterSaveFailedTriggerContextDiscoveryStrategy; - readonly ITriggerService _triggerService = triggerService ?? throw new ArgumentNullException(nameof(triggerService)); - readonly TriggerSessionConfiguration _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); - readonly ITriggerDiscoveryService _triggerDiscoveryService = triggerDiscoveryService ?? throw new ArgumentNullException(nameof(triggerDiscoveryService)); - readonly TriggerContextTracker _tracker = tracker ?? throw new ArgumentNullException(nameof(tracker)); - readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + readonly ITriggerService _triggerService = triggerService ?? throw new ArgumentNullException(nameof(triggerService)); + readonly TriggerSessionConfiguration _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + readonly ITriggerDiscoveryService _triggerDiscoveryService = triggerDiscoveryService ?? throw new ArgumentNullException(nameof(triggerDiscoveryService)); + readonly TriggerContextTracker _tracker = tracker ?? throw new ArgumentNullException(nameof(tracker)); + readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - readonly EntityBagStateManager _entityBagStateManager = new(); + readonly EntityBagStateManager _entityBagStateManager = new(); - bool _raiseBeforeSaveTriggersCalled; - bool _raiseBeforeSaveAsyncTriggersCalled; + bool _raiseBeforeSaveTriggersCalled; + bool _raiseBeforeSaveAsyncTriggersCalled; - public TriggerContextTracker Tracker => _tracker; + public TriggerContextTracker Tracker => _tracker; - public ITriggerDiscoveryService DiscoveryService => _triggerDiscoveryService; + public ITriggerDiscoveryService DiscoveryService => _triggerDiscoveryService; - [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1806:Do not ignore method results", Justification = "Incorrect warning")] - public void DiscoverChanges() - => _tracker.DiscoverChanges().Count(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1806:Do not ignore method results", Justification = "Incorrect warning")] + public void DiscoverChanges() + => _tracker.DiscoverChanges().Count(); - public void RaiseTriggers(Type openTriggerType, Exception? exception, ITriggerContextDiscoveryStrategy triggerContextDiscoveryStrategy, Func triggerTypeDescriptorFactory) + public void RaiseTriggers(Type openTriggerType, Exception? exception, ITriggerContextDiscoveryStrategy triggerContextDiscoveryStrategy, Func triggerTypeDescriptorFactory) + { + ArgumentNullException.ThrowIfNull(triggerContextDiscoveryStrategy); + + if (_configuration.Disabled) { - ArgumentNullException.ThrowIfNull(triggerContextDiscoveryStrategy); + return; + } - if (_configuration.Disabled) - { - return; - } + var triggerContextDescriptorBatches = triggerContextDiscoveryStrategy.Discover(_configuration, _tracker, _logger); + foreach (var triggerContextDescriptorBatch in triggerContextDescriptorBatches) + { + List<(TriggerContextDescriptor triggerContextDescriptor, TriggerDescriptor triggerDescriptor)>? triggerInvocations = null; - var triggerContextDescriptorBatches = triggerContextDiscoveryStrategy.Discover(_configuration, _tracker, _logger); - foreach (var triggerContextDescriptorBatch in triggerContextDescriptorBatches) + foreach (var triggerContextDescriptor in triggerContextDescriptorBatch) { - List<(TriggerContextDescriptor triggerContextDescriptor, TriggerDescriptor triggerDescriptor)>? triggerInvocations = null; + var triggerDescriptors = _triggerDiscoveryService.DiscoverTriggers(openTriggerType, triggerContextDescriptor.EntityType, triggerTypeDescriptorFactory); - foreach (var triggerContextDescriptor in triggerContextDescriptorBatch) + foreach (var triggerDescriptor in triggerDescriptors) { - var triggerDescriptors = _triggerDiscoveryService.DiscoverTriggers(openTriggerType, triggerContextDescriptor.EntityType, triggerTypeDescriptorFactory); - - foreach (var triggerDescriptor in triggerDescriptors) - { - triggerInvocations ??= []; + triggerInvocations ??= []; - triggerInvocations.Add((triggerContextDescriptor, triggerDescriptor)); - } + triggerInvocations.Add((triggerContextDescriptor, triggerDescriptor)); } + } - if (_logger.IsEnabled(LogLevel.Debug)) - { - _logger.LogDebug("Discovered {triggers} triggers of type {openTriggerType}", triggerInvocations?.Count ?? 0, openTriggerType); - } + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug("Discovered {triggers} triggers of type {openTriggerType}", triggerInvocations?.Count ?? 0, openTriggerType); + } - if (triggerInvocations != null) + if (triggerInvocations != null) + { + foreach (var (triggerContextDescriptor, triggerDescriptor) in triggerInvocations.OrderBy(x => x.triggerDescriptor.Priority)) { - foreach (var (triggerContextDescriptor, triggerDescriptor) in triggerInvocations.OrderBy(x => x.triggerDescriptor.Priority)) + if (_logger.IsEnabled(LogLevel.Information)) { - if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("Invoking trigger: {trigger} as {triggerType}", triggerDescriptor.Trigger.GetType(), triggerDescriptor.TypeDescriptor.TriggerType); - } - - triggerDescriptor.Invoke(triggerContextDescriptor.GetTriggerContext(_entityBagStateManager), exception); + _logger.LogInformation("Invoking trigger: {trigger} as {triggerType}", triggerDescriptor.Trigger.GetType(), triggerDescriptor.TypeDescriptor.TriggerType); } - } + triggerDescriptor.Invoke(triggerContextDescriptor.GetTriggerContext(_entityBagStateManager), exception); + } } + } + } - public async Task RaiseAsyncTriggers(Type openTriggerType, Exception? exception, ITriggerContextDiscoveryStrategy triggerContextDiscoveryStrategy, Func triggerTypeDescriptorFactory, CancellationToken cancellationToken) + public async Task RaiseAsyncTriggers(Type openTriggerType, Exception? exception, ITriggerContextDiscoveryStrategy triggerContextDiscoveryStrategy, Func triggerTypeDescriptorFactory, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(triggerContextDiscoveryStrategy); + + if (_configuration.Disabled) { - ArgumentNullException.ThrowIfNull(triggerContextDiscoveryStrategy); + return; + } - if (_configuration.Disabled) - { - return; - } + cancellationToken.ThrowIfCancellationRequested(); - cancellationToken.ThrowIfCancellationRequested(); + var triggerContextDescriptorBatches = triggerContextDiscoveryStrategy.Discover(_configuration, _tracker, _logger); + foreach (var triggerContextDescriptorBatch in triggerContextDescriptorBatches) + { + List<(TriggerContextDescriptor triggerContextDescriptor, AsyncTriggerDescriptor triggerDescriptor)>? triggerInvocations = null; - var triggerContextDescriptorBatches = triggerContextDiscoveryStrategy.Discover(_configuration, _tracker, _logger); - foreach (var triggerContextDescriptorBatch in triggerContextDescriptorBatches) + foreach (var triggerContextDescriptor in triggerContextDescriptorBatch) { - List<(TriggerContextDescriptor triggerContextDescriptor, AsyncTriggerDescriptor triggerDescriptor)>? triggerInvocations = null; + var triggerDescriptors = _triggerDiscoveryService.DiscoverAsyncTriggers(openTriggerType, triggerContextDescriptor.EntityType, triggerTypeDescriptorFactory); - foreach (var triggerContextDescriptor in triggerContextDescriptorBatch) + foreach (var triggerDescriptor in triggerDescriptors) { - var triggerDescriptors = _triggerDiscoveryService.DiscoverAsyncTriggers(openTriggerType, triggerContextDescriptor.EntityType, triggerTypeDescriptorFactory); - - foreach (var triggerDescriptor in triggerDescriptors) - { - triggerInvocations ??= []; + triggerInvocations ??= []; - triggerInvocations.Add((triggerContextDescriptor, triggerDescriptor)); - } + triggerInvocations.Add((triggerContextDescriptor, triggerDescriptor)); } + } - if (_logger.IsEnabled(LogLevel.Debug)) - { - _logger.LogDebug("Discovered {triggers} triggers of type {openTriggerType}", triggerInvocations?.Count ?? 0, openTriggerType); - } + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug("Discovered {triggers} triggers of type {openTriggerType}", triggerInvocations?.Count ?? 0, openTriggerType); + } - if (triggerInvocations != null) + if (triggerInvocations != null) + { + foreach (var (triggerContextDescriptor, triggerDescriptor) in triggerInvocations.OrderBy(x => x.triggerDescriptor.Priority)) { - foreach (var (triggerContextDescriptor, triggerDescriptor) in triggerInvocations.OrderBy(x => x.triggerDescriptor.Priority)) - { - cancellationToken.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); - if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("Invoking trigger: {trigger} as {triggerType}", triggerDescriptor.Trigger.GetType(), triggerDescriptor.TypeDescriptor.TriggerType); - } - - await triggerDescriptor.Invoke(triggerContextDescriptor.GetTriggerContext(_entityBagStateManager), exception, cancellationToken).ConfigureAwait(false); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Invoking trigger: {trigger} as {triggerType}", triggerDescriptor.Trigger.GetType(), triggerDescriptor.TypeDescriptor.TriggerType); } - } + await triggerDescriptor.Invoke(triggerContextDescriptor.GetTriggerContext(_entityBagStateManager), exception, cancellationToken).ConfigureAwait(false); + } } - } - - public void RaiseBeforeSaveStartingTriggers() - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - trigger.BeforeSaveStarting(); - } } + } - public async Task RaiseBeforeSaveStartingAsyncTriggers(CancellationToken cancellationToken) - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + public void RaiseBeforeSaveStartingTriggers() + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - await trigger.BeforeSaveStartingAsync(cancellationToken); - } + foreach (var trigger in triggers) + { + trigger.BeforeSaveStarting(); } + } - public void RaiseBeforeSaveTriggers() - => RaiseBeforeSaveTriggers(_raiseBeforeSaveTriggersCalled); + public async Task RaiseBeforeSaveStartingAsyncTriggers(CancellationToken cancellationToken) + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - public void RaiseBeforeSaveTriggers(bool skipDetectedChanges) + foreach (var trigger in triggers) { - _raiseBeforeSaveTriggersCalled = true; + await trigger.BeforeSaveStartingAsync(cancellationToken); + } + } - ITriggerContextDiscoveryStrategy? strategy; + public void RaiseBeforeSaveTriggers() + => RaiseBeforeSaveTriggers(_raiseBeforeSaveTriggersCalled); - if (skipDetectedChanges) - { - _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", true); + public void RaiseBeforeSaveTriggers(bool skipDetectedChanges) + { + _raiseBeforeSaveTriggersCalled = true; - strategy = _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges; - } - else - { - _beforeSaveTriggerContextDiscoveryStrategy ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", false); + ITriggerContextDiscoveryStrategy? strategy; - strategy = _beforeSaveTriggerContextDiscoveryStrategy; - } + if (skipDetectedChanges) + { + _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", true); - _raiseBeforeSaveTriggersCalled = true; - RaiseTriggers(typeof(IBeforeSaveTrigger<>), null, strategy, entityType => new BeforeSaveTriggerDescriptor(entityType)); + strategy = _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges; } - - public Task RaiseBeforeSaveAsyncTriggers(CancellationToken cancellationToken) - => RaiseBeforeSaveAsyncTriggers(_raiseBeforeSaveAsyncTriggersCalled, cancellationToken); - - public Task RaiseBeforeSaveAsyncTriggers(bool skipDetectedChanges, CancellationToken cancellationToken) + else { - _raiseBeforeSaveAsyncTriggersCalled = true; + _beforeSaveTriggerContextDiscoveryStrategy ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", false); - ITriggerContextDiscoveryStrategy? strategy; + strategy = _beforeSaveTriggerContextDiscoveryStrategy; + } - if (skipDetectedChanges) - { - _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", true); + _raiseBeforeSaveTriggersCalled = true; + RaiseTriggers(typeof(IBeforeSaveTrigger<>), null, strategy, entityType => new BeforeSaveTriggerDescriptor(entityType)); + } - strategy = _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges; - } - else - { - _beforeSaveTriggerContextDiscoveryStrategy ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", false); + public Task RaiseBeforeSaveAsyncTriggers(CancellationToken cancellationToken) + => RaiseBeforeSaveAsyncTriggers(_raiseBeforeSaveAsyncTriggersCalled, cancellationToken); - strategy = _beforeSaveTriggerContextDiscoveryStrategy; - } + public Task RaiseBeforeSaveAsyncTriggers(bool skipDetectedChanges, CancellationToken cancellationToken) + { + _raiseBeforeSaveAsyncTriggersCalled = true; - _raiseBeforeSaveTriggersCalled = true; - return RaiseAsyncTriggers(typeof(IBeforeSaveAsyncTrigger<>), null, strategy, entityType => new BeforeSaveAsyncTriggerDescriptor(entityType), cancellationToken); - } + ITriggerContextDiscoveryStrategy? strategy; - public void RaiseBeforeSaveCompletedTriggers() + if (skipDetectedChanges) { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", true); - foreach (var trigger in triggers) - { - trigger.BeforeSaveCompleted(); - } + strategy = _beforeSaveTriggerContextDiscoveryStrategyWithSkipDetectedChanges; } - - public async Task RaiseBeforeSaveCompletedAsyncTriggers(CancellationToken cancellationToken) + else { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + _beforeSaveTriggerContextDiscoveryStrategy ??= new CascadingTriggerContextDiscoveryStrategy("BeforeSave", false); - foreach (var trigger in triggers) - { - await trigger.BeforeSaveCompletedAsync(cancellationToken); - } + strategy = _beforeSaveTriggerContextDiscoveryStrategy; } - public void CaptureDiscoveredChanges() => _tracker.CaptureChanges(); + _raiseBeforeSaveTriggersCalled = true; + return RaiseAsyncTriggers(typeof(IBeforeSaveAsyncTrigger<>), null, strategy, entityType => new BeforeSaveAsyncTriggerDescriptor(entityType), cancellationToken); + } - public void RaiseAfterSaveStartingTriggers() - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + public void RaiseBeforeSaveCompletedTriggers() + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - trigger.AfterSaveStarting(); - } + foreach (var trigger in triggers) + { + trigger.BeforeSaveCompleted(); } + } - public async Task RaiseAfterSaveStartingAsyncTriggers(CancellationToken cancellationToken) - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + public async Task RaiseBeforeSaveCompletedAsyncTriggers(CancellationToken cancellationToken) + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - await trigger.AfterSaveStartingAsync(cancellationToken); - } + foreach (var trigger in triggers) + { + await trigger.BeforeSaveCompletedAsync(cancellationToken); } + } - public void RaiseAfterSaveTriggers() - { - _afterSaveTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSave"); + public void CaptureDiscoveredChanges() => _tracker.CaptureChanges(); - RaiseTriggers(typeof(IAfterSaveTrigger<>), null, _afterSaveTriggerContextDiscoveryStrategy, entityType => new AfterSaveTriggerDescriptor(entityType)); - } + public void RaiseAfterSaveStartingTriggers() + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - public Task RaiseAfterSaveAsyncTriggers(CancellationToken cancellationToken = default) + foreach (var trigger in triggers) { - _afterSaveTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSave"); - - return RaiseAsyncTriggers(typeof(IAfterSaveAsyncTrigger<>), null, _afterSaveTriggerContextDiscoveryStrategy, entityType => new AfterSaveAsyncTriggerDescriptor(entityType), cancellationToken); + trigger.AfterSaveStarting(); } + } - public void RaiseAfterSaveCompletedTriggers() - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + public async Task RaiseAfterSaveStartingAsyncTriggers(CancellationToken cancellationToken) + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - trigger.AfterSaveCompleted(); - } + foreach (var trigger in triggers) + { + await trigger.AfterSaveStartingAsync(cancellationToken); } + } - public async Task RaiseAfterSaveCompletedAsyncTriggers(CancellationToken cancellationToken) - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + public void RaiseAfterSaveTriggers() + { + _afterSaveTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSave"); - foreach (var trigger in triggers) - { - await trigger.AfterSaveCompletedAsync(cancellationToken); - } - } + RaiseTriggers(typeof(IAfterSaveTrigger<>), null, _afterSaveTriggerContextDiscoveryStrategy, entityType => new AfterSaveTriggerDescriptor(entityType)); + } - public void RaiseAfterSaveFailedStartingTriggers(Exception exception) - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + public Task RaiseAfterSaveAsyncTriggers(CancellationToken cancellationToken = default) + { + _afterSaveTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSave"); - foreach (var trigger in triggers) - { - trigger.AfterSaveFailedStarting(exception); - } - } + return RaiseAsyncTriggers(typeof(IAfterSaveAsyncTrigger<>), null, _afterSaveTriggerContextDiscoveryStrategy, entityType => new AfterSaveAsyncTriggerDescriptor(entityType), cancellationToken); + } - public async Task RaiseAfterSaveFailedStartingAsyncTriggers(Exception exception, CancellationToken cancellationToken) - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + public void RaiseAfterSaveCompletedTriggers() + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - await trigger.AfterSaveFailedStartingAsync(exception, cancellationToken); - } + foreach (var trigger in triggers) + { + trigger.AfterSaveCompleted(); } + } - public void RaiseAfterSaveFailedTriggers(Exception exception) - { - _afterSaveFailedTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSaveFailed"); + public async Task RaiseAfterSaveCompletedAsyncTriggers(CancellationToken cancellationToken) + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - RaiseTriggers(typeof(IAfterSaveFailedTrigger<>), exception, _afterSaveFailedTriggerContextDiscoveryStrategy, entityType => new AfterSaveFailedTriggerDescriptor(entityType)); + foreach (var trigger in triggers) + { + await trigger.AfterSaveCompletedAsync(cancellationToken); } + } - public Task RaiseAfterSaveFailedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) - { - _afterSaveFailedTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSaveFailed"); + public void RaiseAfterSaveFailedStartingTriggers(Exception exception) + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - return RaiseAsyncTriggers(typeof(IAfterSaveFailedAsyncTrigger<>), exception, _afterSaveFailedTriggerContextDiscoveryStrategy, entityType => new AfterSaveFailedAsyncTriggerDescriptor(entityType), cancellationToken); + foreach (var trigger in triggers) + { + trigger.AfterSaveFailedStarting(exception); } + } - public void RaiseAfterSaveFailedCompletedTriggers(Exception exception) - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + public async Task RaiseAfterSaveFailedStartingAsyncTriggers(Exception exception, CancellationToken cancellationToken) + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); - foreach (var trigger in triggers) - { - trigger.AfterSaveFailedCompleted(exception); - } + foreach (var trigger in triggers) + { + await trigger.AfterSaveFailedStartingAsync(exception, cancellationToken); } + } - public async Task RaiseAfterSaveFailedCompletedAsyncTriggers(Exception exception, CancellationToken cancellationToken) - { - var triggers = _triggerDiscoveryService.DiscoverTriggers(); + public void RaiseAfterSaveFailedTriggers(Exception exception) + { + _afterSaveFailedTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSaveFailed"); - foreach (var trigger in triggers) - { - await trigger.AfterSaveFailedCompletedAsync(exception, cancellationToken); - } + RaiseTriggers(typeof(IAfterSaveFailedTrigger<>), exception, _afterSaveFailedTriggerContextDiscoveryStrategy, entityType => new AfterSaveFailedTriggerDescriptor(entityType)); + } + + public Task RaiseAfterSaveFailedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) + { + _afterSaveFailedTriggerContextDiscoveryStrategy ??= new NonCascadingTriggerContextDiscoveryStrategy("AfterSaveFailed"); + + return RaiseAsyncTriggers(typeof(IAfterSaveFailedAsyncTrigger<>), exception, _afterSaveFailedTriggerContextDiscoveryStrategy, entityType => new AfterSaveFailedAsyncTriggerDescriptor(entityType), cancellationToken); + } + + public void RaiseAfterSaveFailedCompletedTriggers(Exception exception) + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); + + foreach (var trigger in triggers) + { + trigger.AfterSaveFailedCompleted(exception); } + } - public void Dispose() + public async Task RaiseAfterSaveFailedCompletedAsyncTriggers(Exception exception, CancellationToken cancellationToken) + { + var triggers = _triggerDiscoveryService.DiscoverTriggers(); + + foreach (var trigger in triggers) { - if (_triggerService.Current == this) - { - _triggerService.Current = null; - } + await trigger.AfterSaveFailedCompletedAsync(exception, cancellationToken); + } + } - GC.SuppressFinalize(this); + public void Dispose() + { + if (_triggerService.Current == this) + { + _triggerService.Current = null; } + + GC.SuppressFinalize(this); } } diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs index a0e975a..f59c148 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/AbstractTrigger.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.Extensions.Tests +namespace EntityFrameworkCore.Triggered.Extensions.Tests; + +public abstract class AbstractTrigger : IBeforeSaveTrigger { - public abstract class AbstractTrigger : IBeforeSaveTrigger - { - public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); - } + public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); } diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTrigger.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTrigger.cs index d183c9b..0a07ec2 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTrigger.cs @@ -1,31 +1,30 @@ using EntityFrameworkCore.Triggered.Lifecycles; -namespace EntityFrameworkCore.Triggered.Extensions.Tests +namespace EntityFrameworkCore.Triggered.Extensions.Tests; + +public class SampleTrigger : Trigger, IBeforeSaveStartingAsyncTrigger { - public class SampleTrigger : Trigger, IBeforeSaveStartingAsyncTrigger - { - public int BeforeSaveCalls; - public int BeforeSaveAsyncCalls; + public int BeforeSaveCalls; + public int BeforeSaveAsyncCalls; - public int AfterSaveCalls; - public int AfterSaveAsyncCalls; + public int AfterSaveCalls; + public int AfterSaveAsyncCalls; - public int AfterSaveFailedCalls; - public int AfterSaveFailedAsyncCalls; + public int AfterSaveFailedCalls; + public int AfterSaveFailedAsyncCalls; - public int BeforeSaveStartingTriggerCalls; + public int BeforeSaveStartingTriggerCalls; #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - public override void BeforeSave(ITriggerContext context) => BeforeSaveCalls += 1; - public override async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => BeforeSaveAsyncCalls += 1; + public override void BeforeSave(ITriggerContext context) => BeforeSaveCalls += 1; + public override async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => BeforeSaveAsyncCalls += 1; - public override void AfterSave(ITriggerContext context) => AfterSaveCalls += 1; - public override async Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => AfterSaveAsyncCalls += 1; + public override void AfterSave(ITriggerContext context) => AfterSaveCalls += 1; + public override async Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => AfterSaveAsyncCalls += 1; - public override void AfterSaveFailed(ITriggerContext context, Exception exception) => AfterSaveFailedCalls += 1; - public override async Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken) => AfterSaveFailedAsyncCalls += 1; - public async Task BeforeSaveStartingAsync(CancellationToken cancellationToken) => BeforeSaveStartingTriggerCalls += 1; + public override void AfterSaveFailed(ITriggerContext context, Exception exception) => AfterSaveFailedCalls += 1; + public override async Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken) => AfterSaveFailedAsyncCalls += 1; + public async Task BeforeSaveStartingAsync(CancellationToken cancellationToken) => BeforeSaveStartingTriggerCalls += 1; #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously - } } diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTriggerClone.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTriggerClone.cs index 796e7cc..c6f18fc 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTriggerClone.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/SampleTriggerClone.cs @@ -1,31 +1,30 @@ using EntityFrameworkCore.Triggered.Lifecycles; -namespace EntityFrameworkCore.Triggered.Extensions.Tests +namespace EntityFrameworkCore.Triggered.Extensions.Tests; + +public class SampleTriggerClone : Trigger, IBeforeSaveStartingAsyncTrigger { - public class SampleTriggerClone : Trigger, IBeforeSaveStartingAsyncTrigger - { - public int BeforeSaveCalls; - public int BeforeSaveAsyncCalls; + public int BeforeSaveCalls; + public int BeforeSaveAsyncCalls; - public int AfterSaveCalls; - public int AfterSaveAsyncCalls; + public int AfterSaveCalls; + public int AfterSaveAsyncCalls; - public int AfterSaveFailedCalls; - public int AfterSaveFailedAsyncCalls; + public int AfterSaveFailedCalls; + public int AfterSaveFailedAsyncCalls; - public int BeforeSaveStartingTriggerCalls; + public int BeforeSaveStartingTriggerCalls; #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - public override void BeforeSave(ITriggerContext context) => BeforeSaveCalls += 1; - public override async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => BeforeSaveAsyncCalls += 1; + public override void BeforeSave(ITriggerContext context) => BeforeSaveCalls += 1; + public override async Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => BeforeSaveAsyncCalls += 1; - public override void AfterSave(ITriggerContext context) => AfterSaveCalls += 1; - public override async Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => AfterSaveAsyncCalls += 1; + public override void AfterSave(ITriggerContext context) => AfterSaveCalls += 1; + public override async Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => AfterSaveAsyncCalls += 1; - public override void AfterSaveFailed(ITriggerContext context, Exception exception) => AfterSaveFailedCalls += 1; - public override async Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken) => AfterSaveFailedAsyncCalls += 1; - public async Task BeforeSaveStartingAsync(CancellationToken cancellationToken) => BeforeSaveStartingTriggerCalls += 1; + public override void AfterSaveFailed(ITriggerContext context, Exception exception) => AfterSaveFailedCalls += 1; + public override async Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken) => AfterSaveFailedAsyncCalls += 1; + public async Task BeforeSaveStartingAsync(CancellationToken cancellationToken) => BeforeSaveStartingTriggerCalls += 1; #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously - } } diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs index 45c7feb..61622a6 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs @@ -3,239 +3,238 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Extensions.Tests +namespace EntityFrameworkCore.Triggered.Extensions.Tests; + +public class ServiceCollectionExtensionsTests { - public class ServiceCollectionExtensionsTests - { - public static IEnumerable Lifetimes() - { - yield return new object[] { ServiceLifetime.Transient }; - yield return new object[] { ServiceLifetime.Scoped }; - yield return new object[] { ServiceLifetime.Singleton }; - } - - public static IEnumerable TriggerTypes() - { - yield return new object[] { typeof(IBeforeSaveTrigger) }; - yield return new object[] { typeof(IAfterSaveTrigger) }; - yield return new object[] { typeof(IAfterSaveFailedTrigger) }; - } - - public class TestModel - { - public int Id { get; set; } - } - - public class TestDbContext(DbContextOptions options) : DbContext(options) - { - public DbSet TestModels { get; set; } - } - - [Theory] - [MemberData(nameof(Lifetimes))] - public void AddTriggerOfT_WithCustomLifetime_RegistersWithThatLifetime(ServiceLifetime lifetime) - { - var serviceCollection = new ServiceCollection() - .AddTrigger>(lifetime); - - Assert.Equal(lifetime, serviceCollection.First().Lifetime); - } - - [Theory] - [MemberData(nameof(TriggerTypes))] - public void AddTriggerOfT_RegistersAllLifetimes(Type triggerLifetimeType) - { - var serviceCollection = new ServiceCollection() - .AddTrigger>(); - - Assert.Contains(serviceCollection, x => x.ServiceType == triggerLifetimeType); - } - - [Theory] - [MemberData(nameof(TriggerTypes))] - public void AddTriggerInstance_RegistersAllTypes(Type triggerLifetimeType) - { - var serviceCollection = new ServiceCollection() - .AddTrigger(new Trigger()); - - Assert.Contains(serviceCollection, x => x.ServiceType == triggerLifetimeType); - } - - [Theory] - [MemberData(nameof(Lifetimes))] - public void AddAssemblyTriggers_WithCustomLifetime_RegistersWithThatLifetime(ServiceLifetime lifetime) - { - var serviceCollection = new ServiceCollection() - .AddAssemblyTriggers(lifetime); - - Assert.Equal(lifetime, serviceCollection.First().Lifetime); - } - - [Fact] - public void AddAssemblyTriggers_WithAssembly_RegistersWithThatAssembly() - { - var serviceCollection = new ServiceCollection() - .AddAssemblyTriggers(typeof(ServiceCollectionExtensionsTests).Assembly); - - Assert.Equal(16, serviceCollection.Count); - } - - protected async Task SaveChanges_TriggeredAddedThroughDI_Template(Func transform) - { - var services = transform(new ServiceCollection() - .AddTriggeredDbContext(options => { - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - })); - - var serviceProvider = services - .BuildServiceProvider(); - - using var dbContext = serviceProvider.GetRequiredService(); - dbContext.TestModels.Add(new TestModel { }); - - await dbContext.SaveChangesAsync(); - - var trigger = serviceProvider.GetRequiredService(); - var triggerClone = serviceProvider.GetRequiredService(); - - Assert.Equal(1, trigger.BeforeSaveStartingTriggerCalls); - Assert.Equal(1, trigger.BeforeSaveCalls); - Assert.Equal(1, trigger.BeforeSaveAsyncCalls); - Assert.Equal(1, trigger.AfterSaveCalls); - Assert.Equal(1, trigger.AfterSaveAsyncCalls); - - Assert.Equal(1, triggerClone.BeforeSaveStartingTriggerCalls); - Assert.Equal(1, triggerClone.BeforeSaveCalls); - Assert.Equal(1, triggerClone.BeforeSaveAsyncCalls); - Assert.Equal(1, triggerClone.AfterSaveCalls); - Assert.Equal(1, triggerClone.AfterSaveAsyncCalls); - } - - [Fact] - public Task SaveChanges_ExplicitlyAddedTriggerThroughDI_RaisesAllTriggerTypes() - => SaveChanges_TriggeredAddedThroughDI_Template(x => { - x.AddTrigger(); - x.AddTrigger(); - - return x; - }); - - [Fact] - public Task SaveChanges_DiscoveredTriggerThroughDI_RaisesAllTriggerTypes() - => SaveChanges_TriggeredAddedThroughDI_Template(x => x.AddAssemblyTriggers()); - - [Fact] - public void AddAssemblyTriggers_AbstractTrigger_GetsIgnored() - { - var serviceCollection = new ServiceCollection() - .AddAssemblyTriggers(); - - // Ensure that we did not register the AbstractTrigger - Assert.Empty(serviceCollection.Where(x => x.ImplementationType == typeof(AbstractTrigger))); - } - - [Theory] - [MemberData(nameof(Lifetimes))] - public void AddTrigger_Multiple_AddsRegistrationForAll(ServiceLifetime lifetime) - { - var serviceCollection = new ServiceCollection() - .AddTrigger(lifetime) - .AddTrigger(lifetime) - .AddTrigger>(lifetime); - - Assert.Equal(23, serviceCollection.Count); - } - - [Theory] - [MemberData(nameof(Lifetimes))] - public void AddAssemblyTriggers_Multiple_AddsRegistrationForAll(ServiceLifetime lifetime) - { - var serviceCollection = new ServiceCollection() - .AddTrigger(lifetime) - .AddTrigger(lifetime) - .AddAssemblyTriggers(typeof(Trigger).Assembly); - - Assert.Equal(23, serviceCollection.Count); - } - - [Fact] - public void AddTriggerInstance_DoesNotDoubleRegister() - { - var trigger = new SampleTrigger(); - - var serviceCollection = new ServiceCollection() - .AddTrigger(trigger) - .AddTrigger(trigger); - - Assert.Single(serviceCollection, x => x.ImplementationInstance == trigger); - } - - [Theory] - [MemberData(nameof(Lifetimes))] - public void AddTrigger_DoesNotDoubleRegister(ServiceLifetime lifetime) - { - var serviceCollection = new ServiceCollection() - .AddTrigger(lifetime) - .AddTrigger(lifetime); - - Assert.Single(serviceCollection, x => x.ServiceType == typeof(SampleTrigger)); - } - - [Theory] - [MemberData(nameof(Lifetimes))] - public void AddTrigger_DoesNotDoubleRegister2(ServiceLifetime lifetime) - { - var serviceCollection = new ServiceCollection() - .AddAssemblyTriggers(lifetime) - .AddTrigger(lifetime); - - Assert.Single(serviceCollection, x => x.ServiceType == typeof(SampleTrigger)); - } - - [Theory] - [MemberData(nameof(Lifetimes))] - public void AddAssemblyTrigger_DoesNotDoubleRegister(ServiceLifetime lifetime) - { - var serviceCollection = new ServiceCollection() - .AddAssemblyTriggers(lifetime) - .AddAssemblyTriggers(lifetime); - - Assert.Single(serviceCollection, x => x.ServiceType == typeof(SampleTrigger)); - } - - [Theory] - [MemberData(nameof(Lifetimes))] - public void AddAssemblyTrigger_DoesNotDoubleRegister2(ServiceLifetime lifetime) - { - var serviceCollection = new ServiceCollection() - .AddTrigger(lifetime) - .AddAssemblyTriggers(lifetime); - - Assert.Single(serviceCollection, x => x.ServiceType == typeof(SampleTrigger)); - } - - [Fact] - public void AddTrigger_WhenExplicitlyRegisteredAsAService_OnlyAddsTheTriggerTypeRegistrations() - { - var serviceCollection = new ServiceCollection() - .AddSingleton() - .AddTrigger(); - - Assert.Equal(8, serviceCollection.Count); - } - - [Fact] - public void AddAssemblyTriggers_WhenExplicitlyRegisteredAsAService_OnlyAddsTheTriggerTypeRegistrations() - { - var serviceCollection = new ServiceCollection() - .AddSingleton() - .AddSingleton() - .AddAssemblyTriggers(); - - Assert.Equal(16, serviceCollection.Count); - } + public static IEnumerable Lifetimes() + { + yield return new object[] { ServiceLifetime.Transient }; + yield return new object[] { ServiceLifetime.Scoped }; + yield return new object[] { ServiceLifetime.Singleton }; + } + + public static IEnumerable TriggerTypes() + { + yield return new object[] { typeof(IBeforeSaveTrigger) }; + yield return new object[] { typeof(IAfterSaveTrigger) }; + yield return new object[] { typeof(IAfterSaveFailedTrigger) }; + } + + public class TestModel + { + public int Id { get; set; } + } + + public class TestDbContext(DbContextOptions options) : DbContext(options) + { + public DbSet TestModels { get; set; } + } + + [Theory] + [MemberData(nameof(Lifetimes))] + public void AddTriggerOfT_WithCustomLifetime_RegistersWithThatLifetime(ServiceLifetime lifetime) + { + var serviceCollection = new ServiceCollection() + .AddTrigger>(lifetime); + + Assert.Equal(lifetime, serviceCollection.First().Lifetime); + } + + [Theory] + [MemberData(nameof(TriggerTypes))] + public void AddTriggerOfT_RegistersAllLifetimes(Type triggerLifetimeType) + { + var serviceCollection = new ServiceCollection() + .AddTrigger>(); + + Assert.Contains(serviceCollection, x => x.ServiceType == triggerLifetimeType); + } + + [Theory] + [MemberData(nameof(TriggerTypes))] + public void AddTriggerInstance_RegistersAllTypes(Type triggerLifetimeType) + { + var serviceCollection = new ServiceCollection() + .AddTrigger(new Trigger()); + + Assert.Contains(serviceCollection, x => x.ServiceType == triggerLifetimeType); + } + + [Theory] + [MemberData(nameof(Lifetimes))] + public void AddAssemblyTriggers_WithCustomLifetime_RegistersWithThatLifetime(ServiceLifetime lifetime) + { + var serviceCollection = new ServiceCollection() + .AddAssemblyTriggers(lifetime); + + Assert.Equal(lifetime, serviceCollection.First().Lifetime); + } + + [Fact] + public void AddAssemblyTriggers_WithAssembly_RegistersWithThatAssembly() + { + var serviceCollection = new ServiceCollection() + .AddAssemblyTriggers(typeof(ServiceCollectionExtensionsTests).Assembly); + + Assert.Equal(16, serviceCollection.Count); + } + + protected async Task SaveChanges_TriggeredAddedThroughDI_Template(Func transform) + { + var services = transform(new ServiceCollection() + .AddTriggeredDbContext(options => { + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + })); + + var serviceProvider = services + .BuildServiceProvider(); + + using var dbContext = serviceProvider.GetRequiredService(); + dbContext.TestModels.Add(new TestModel { }); + + await dbContext.SaveChangesAsync(); + + var trigger = serviceProvider.GetRequiredService(); + var triggerClone = serviceProvider.GetRequiredService(); + + Assert.Equal(1, trigger.BeforeSaveStartingTriggerCalls); + Assert.Equal(1, trigger.BeforeSaveCalls); + Assert.Equal(1, trigger.BeforeSaveAsyncCalls); + Assert.Equal(1, trigger.AfterSaveCalls); + Assert.Equal(1, trigger.AfterSaveAsyncCalls); + + Assert.Equal(1, triggerClone.BeforeSaveStartingTriggerCalls); + Assert.Equal(1, triggerClone.BeforeSaveCalls); + Assert.Equal(1, triggerClone.BeforeSaveAsyncCalls); + Assert.Equal(1, triggerClone.AfterSaveCalls); + Assert.Equal(1, triggerClone.AfterSaveAsyncCalls); + } + + [Fact] + public Task SaveChanges_ExplicitlyAddedTriggerThroughDI_RaisesAllTriggerTypes() + => SaveChanges_TriggeredAddedThroughDI_Template(x => { + x.AddTrigger(); + x.AddTrigger(); + + return x; + }); + + [Fact] + public Task SaveChanges_DiscoveredTriggerThroughDI_RaisesAllTriggerTypes() + => SaveChanges_TriggeredAddedThroughDI_Template(x => x.AddAssemblyTriggers()); + + [Fact] + public void AddAssemblyTriggers_AbstractTrigger_GetsIgnored() + { + var serviceCollection = new ServiceCollection() + .AddAssemblyTriggers(); + + // Ensure that we did not register the AbstractTrigger + Assert.Empty(serviceCollection.Where(x => x.ImplementationType == typeof(AbstractTrigger))); + } + + [Theory] + [MemberData(nameof(Lifetimes))] + public void AddTrigger_Multiple_AddsRegistrationForAll(ServiceLifetime lifetime) + { + var serviceCollection = new ServiceCollection() + .AddTrigger(lifetime) + .AddTrigger(lifetime) + .AddTrigger>(lifetime); + + Assert.Equal(23, serviceCollection.Count); + } + + [Theory] + [MemberData(nameof(Lifetimes))] + public void AddAssemblyTriggers_Multiple_AddsRegistrationForAll(ServiceLifetime lifetime) + { + var serviceCollection = new ServiceCollection() + .AddTrigger(lifetime) + .AddTrigger(lifetime) + .AddAssemblyTriggers(typeof(Trigger).Assembly); + + Assert.Equal(23, serviceCollection.Count); + } + + [Fact] + public void AddTriggerInstance_DoesNotDoubleRegister() + { + var trigger = new SampleTrigger(); + + var serviceCollection = new ServiceCollection() + .AddTrigger(trigger) + .AddTrigger(trigger); + + Assert.Single(serviceCollection, x => x.ImplementationInstance == trigger); + } + + [Theory] + [MemberData(nameof(Lifetimes))] + public void AddTrigger_DoesNotDoubleRegister(ServiceLifetime lifetime) + { + var serviceCollection = new ServiceCollection() + .AddTrigger(lifetime) + .AddTrigger(lifetime); + + Assert.Single(serviceCollection, x => x.ServiceType == typeof(SampleTrigger)); + } + + [Theory] + [MemberData(nameof(Lifetimes))] + public void AddTrigger_DoesNotDoubleRegister2(ServiceLifetime lifetime) + { + var serviceCollection = new ServiceCollection() + .AddAssemblyTriggers(lifetime) + .AddTrigger(lifetime); + + Assert.Single(serviceCollection, x => x.ServiceType == typeof(SampleTrigger)); + } + + [Theory] + [MemberData(nameof(Lifetimes))] + public void AddAssemblyTrigger_DoesNotDoubleRegister(ServiceLifetime lifetime) + { + var serviceCollection = new ServiceCollection() + .AddAssemblyTriggers(lifetime) + .AddAssemblyTriggers(lifetime); + + Assert.Single(serviceCollection, x => x.ServiceType == typeof(SampleTrigger)); + } + + [Theory] + [MemberData(nameof(Lifetimes))] + public void AddAssemblyTrigger_DoesNotDoubleRegister2(ServiceLifetime lifetime) + { + var serviceCollection = new ServiceCollection() + .AddTrigger(lifetime) + .AddAssemblyTriggers(lifetime); + + Assert.Single(serviceCollection, x => x.ServiceType == typeof(SampleTrigger)); + } + + [Fact] + public void AddTrigger_WhenExplicitlyRegisteredAsAService_OnlyAddsTheTriggerTypeRegistrations() + { + var serviceCollection = new ServiceCollection() + .AddSingleton() + .AddTrigger(); + + Assert.Equal(8, serviceCollection.Count); + } + + [Fact] + public void AddAssemblyTriggers_WhenExplicitlyRegisteredAsAService_OnlyAddsTheTriggerTypeRegistrations() + { + var serviceCollection = new ServiceCollection() + .AddSingleton() + .AddSingleton() + .AddAssemblyTriggers(); + + Assert.Equal(16, serviceCollection.Count); } } diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextExtensionsTests.cs index 80e2aa2..8fb0264 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextExtensionsTests.cs @@ -2,49 +2,48 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; -namespace EntityFrameworkCore.Triggered.Extensions.Tests +namespace EntityFrameworkCore.Triggered.Extensions.Tests; + +public class TriggerContextExtensionsTests { - public class TriggerContextExtensionsTests + record TestEntity(int Id); + + class SampleDbContext : DbContext { - record TestEntity(int Id); + public DbSet Entities { get; set; } - class SampleDbContext : DbContext + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - public DbSet Entities { get; set; } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseInMemoryDatabase(nameof(TriggerContextExtensionsTests)); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); + optionsBuilder.UseInMemoryDatabase(nameof(TriggerContextExtensionsTests)); + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); - } } + } - [Fact] - public void GetDbContext() - { - using var expected = new SampleDbContext(); - var entity = new TestEntity(1); - var triggerContext = new TriggerContext(expected.Add(entity), null, ChangeType.Added, new Internal.EntityBagStateManager()); + [Fact] + public void GetDbContext() + { + using var expected = new SampleDbContext(); + var entity = new TestEntity(1); + var triggerContext = new TriggerContext(expected.Add(entity), null, ChangeType.Added, new Internal.EntityBagStateManager()); - var actual = triggerContext.GetDbContext(); + var actual = triggerContext.GetDbContext(); - Assert.Equal(expected, actual); - } + Assert.Equal(expected, actual); + } - [Fact] - public void GetEntry() - { - using var dbContext = new SampleDbContext(); - var entity = new TestEntity(1); - var expected = dbContext.Add(entity); - var triggerContext = new TriggerContext(expected, null, ChangeType.Added, new Internal.EntityBagStateManager()); + [Fact] + public void GetEntry() + { + using var dbContext = new SampleDbContext(); + var entity = new TestEntity(1); + var expected = dbContext.Add(entity); + var triggerContext = new TriggerContext(expected, null, ChangeType.Added, new Internal.EntityBagStateManager()); - var actual = triggerContext.GetEntry(); + var actual = triggerContext.GetEntry(); - Assert.Equal(expected, actual); - } + Assert.Equal(expected, actual); } } diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs index 7f78a25..aad4a0b 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs @@ -4,22 +4,21 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Extensions.Tests +namespace EntityFrameworkCore.Triggered.Extensions.Tests; + +public class TriggerContextOptionsBuilderExtensionsTests { - public class TriggerContextOptionsBuilderExtensionsTests + [Fact] + public void AddAssemblyTriggers_AbstractTrigger_GetsIgnored() { - [Fact] - public void AddAssemblyTriggers_AbstractTrigger_GetsIgnored() - { - var context = new DbContextOptionsBuilder(); - var builder = new TriggersContextOptionsBuilder(context); + var context = new DbContextOptionsBuilder(); + var builder = new TriggersContextOptionsBuilder(context); - builder.AddAssemblyTriggers(); + builder.AddAssemblyTriggers(); - var triggerOptionExtension = context.Options.Extensions.OfType().Single(); + var triggerOptionExtension = context.Options.Extensions.OfType().Single(); - // Ensure that we did not register the AbstractTrigger - Assert.Empty(triggerOptionExtension.Triggers.Where(x => ReferenceEquals(x.typeOrInstance, typeof(AbstractTrigger)))); - } + // Ensure that we did not register the AbstractTrigger + Assert.Empty(triggerOptionExtension.Triggers.Where(x => ReferenceEquals(x.typeOrInstance, typeof(AbstractTrigger)))); } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/ApplicationDbContext.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/ApplicationDbContext.cs index 9ce8a13..2f222e1 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/ApplicationDbContext.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/ApplicationDbContext.cs @@ -2,26 +2,23 @@ using EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Triggers; using Microsoft.EntityFrameworkCore; -namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes -{ - public class ApplicationDbContext(string databaseName) : DbContext - { - readonly string _databaseName = databaseName; - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder - .UseInMemoryDatabase(_databaseName) - .UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(); - }); +namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes; - protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() - .HasOne(x => x.Parent) - .WithMany(x => x.Children) - .HasForeignKey(x => x.ParentId) - .OnDelete(DeleteBehavior.Cascade); +public class ApplicationDbContext(string databaseName) : DbContext +{ + readonly string _databaseName = databaseName; - public DbSet Branches => Set(); - } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder + .UseInMemoryDatabase(_databaseName) + .UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(); + }); + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() + .HasOne(x => x.Parent) + .WithMany(x => x.Children) + .HasForeignKey(x => x.ParentId) + .OnDelete(DeleteBehavior.Cascade); + public DbSet Branches => Set(); } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/CascadingSoftDeletesTestScenario.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/CascadingSoftDeletesTestScenario.cs index d58cfc5..bda7119 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/CascadingSoftDeletesTestScenario.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/CascadingSoftDeletesTestScenario.cs @@ -2,51 +2,50 @@ using ScenarioTests; using Xunit; -namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes +namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes; + +public partial class CascadingSoftDeletesTestScenario { - public partial class CascadingSoftDeletesTestScenario + [Scenario(NamingPolicy = ScenarioTestMethodNamingPolicy.Test)] + public void Scenario(ScenarioContext scenario) { - [Scenario(NamingPolicy = ScenarioTestMethodNamingPolicy.Test)] - public void Scenario(ScenarioContext scenario) + var dbContext = new ApplicationDbContext(scenario.TargetName); + + var level0 = new Branch(); + var level1 = new Branch() { Parent = level0 }; + var level2 = new Branch() { Parent = level1 }; + + dbContext.AddRange(level0, level1, level2); { - var dbContext = new ApplicationDbContext(scenario.TargetName); - - var level0 = new Branch(); - var level1 = new Branch() { Parent = level0 }; - var level2 = new Branch() { Parent = level1 }; - - dbContext.AddRange(level0, level1, level2); - { - var result = dbContext.SaveChanges(); - Assert.Equal(3, result); - } - - scenario.Fact("1. Soft delete works on the deepest level", () => { - dbContext.Remove(level2); - var result = dbContext.SaveChanges(); - - Assert.Equal(1, result); - Assert.NotNull(level2.DeletedOn); - }); - - scenario.Fact("2. Soft delete cascades at least 1 level deep", () => { - dbContext.Remove(level1); - var result = dbContext.SaveChanges(); - - Assert.Equal(2, result); - Assert.NotNull(level1.DeletedOn); - Assert.NotNull(level2.DeletedOn); - }); - - scenario.Fact("3. Soft delete cascades multiple levels deep", () => { - dbContext.Remove(level0); - var result = dbContext.SaveChanges(); - - Assert.Equal(3, result); - Assert.NotNull(level0.DeletedOn); - Assert.NotNull(level1.DeletedOn); - Assert.NotNull(level2.DeletedOn); - }); + var result = dbContext.SaveChanges(); + Assert.Equal(3, result); } + + scenario.Fact("1. Soft delete works on the deepest level", () => { + dbContext.Remove(level2); + var result = dbContext.SaveChanges(); + + Assert.Equal(1, result); + Assert.NotNull(level2.DeletedOn); + }); + + scenario.Fact("2. Soft delete cascades at least 1 level deep", () => { + dbContext.Remove(level1); + var result = dbContext.SaveChanges(); + + Assert.Equal(2, result); + Assert.NotNull(level1.DeletedOn); + Assert.NotNull(level2.DeletedOn); + }); + + scenario.Fact("3. Soft delete cascades multiple levels deep", () => { + dbContext.Remove(level0); + var result = dbContext.SaveChanges(); + + Assert.Equal(3, result); + Assert.NotNull(level0.DeletedOn); + Assert.NotNull(level1.DeletedOn); + Assert.NotNull(level2.DeletedOn); + }); } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Models/Branch.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Models/Branch.cs index 1a59100..f7d9315 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Models/Branch.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Models/Branch.cs @@ -1,13 +1,12 @@ -namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Models +namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Models; + +public class Branch { - public class Branch - { - public int Id { get; set; } - public int? ParentId { get; set; } - public DateTime? DeletedOn { get; set; } + public int Id { get; set; } + public int? ParentId { get; set; } + public DateTime? DeletedOn { get; set; } - public Branch Parent { get; set; } - public ICollection Children { get; set; } + public Branch Parent { get; set; } + public ICollection Children { get; set; } - } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs index 49f0e41..99b4632 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/CascadingSoftDeletes/Triggers/SoftDelete.cs @@ -1,19 +1,18 @@ using EntityFrameworkCore.Triggered.Extensions; using EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Models; -namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Triggers +namespace EntityFrameworkCore.Triggered.IntegrationTests.CascadingSoftDeletes.Triggers; + +public class SoftDelete(ApplicationDbContext applicationDbContext) : Trigger { - public class SoftDelete(ApplicationDbContext applicationDbContext) : Trigger - { - readonly ApplicationDbContext _applicationDbContext = applicationDbContext; + readonly ApplicationDbContext _applicationDbContext = applicationDbContext; - public override void BeforeSave(ITriggerContext context) + public override void BeforeSave(ITriggerContext context) + { + if (context.ChangeType is ChangeType.Deleted) { - if (context.ChangeType is ChangeType.Deleted) - { - _applicationDbContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; - context.Entity.DeletedOn = DateTime.UtcNow; - } + _applicationDbContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; + context.Entity.DeletedOn = DateTime.UtcNow; } } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/ApplicationDbContext.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/ApplicationDbContext.cs index cab870b..cdc1ec3 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/ApplicationDbContext.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/ApplicationDbContext.cs @@ -1,9 +1,8 @@ using Microsoft.EntityFrameworkCore; -namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags +namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags; + +public class ApplicationDbContext(DbContextOptions options) : DbContext(options) { - public class ApplicationDbContext(DbContextOptions options) : DbContext(options) - { - public DbSet Users { get; set; } - } + public DbSet Users { get; set; } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/EntityBagsTestScenario.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/EntityBagsTestScenario.cs index b89ab3c..f243683 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/EntityBagsTestScenario.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/EntityBagsTestScenario.cs @@ -2,40 +2,39 @@ using ScenarioTests; using Xunit; -namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags +namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags; + +public partial class EntityBagsTestScenario { - public partial class EntityBagsTestScenario + [Scenario(NamingPolicy = ScenarioTestMethodNamingPolicy.Test)] + public void PlayScenario(ScenarioContext scenario) { - [Scenario(NamingPolicy = ScenarioTestMethodNamingPolicy.Test)] - public void PlayScenario(ScenarioContext scenario) - { - using var dbcontext = new ApplicationDbContext( - new DbContextOptionsBuilder() - .UseInMemoryDatabase(scenario.TargetName) - .UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(); - triggerOptions.AddTrigger(); - }) - .Options - ); - - var user = new User(); - dbcontext.Users.Add(user); - dbcontext.SaveChanges(); - - scenario.Fact("ModifiedOn is null", () => Assert.Null(user.ModifiedOn)); - scenario.Fact("DeletedOn is null", () => Assert.Null(user.DeletedOn)); - - dbcontext.Remove(user); - dbcontext.SaveChanges(); - - scenario.Fact("ModifiedOn is null after removal", () => Assert.Null(user.ModifiedOn)); - scenario.Fact("DeletedOn is not null after removal", () => Assert.NotNull(user.DeletedOn)); - - user.Name = "Jon"; - dbcontext.SaveChanges(); - - scenario.Fact("ModifiedOn is not null after update", () => Assert.NotNull(user.ModifiedOn)); - } + using var dbcontext = new ApplicationDbContext( + new DbContextOptionsBuilder() + .UseInMemoryDatabase(scenario.TargetName) + .UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(); + triggerOptions.AddTrigger(); + }) + .Options + ); + + var user = new User(); + dbcontext.Users.Add(user); + dbcontext.SaveChanges(); + + scenario.Fact("ModifiedOn is null", () => Assert.Null(user.ModifiedOn)); + scenario.Fact("DeletedOn is null", () => Assert.Null(user.DeletedOn)); + + dbcontext.Remove(user); + dbcontext.SaveChanges(); + + scenario.Fact("ModifiedOn is null after removal", () => Assert.Null(user.ModifiedOn)); + scenario.Fact("DeletedOn is not null after removal", () => Assert.NotNull(user.DeletedOn)); + + user.Name = "Jon"; + dbcontext.SaveChanges(); + + scenario.Fact("ModifiedOn is not null after update", () => Assert.NotNull(user.ModifiedOn)); } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs index c19f028..fe7f8bf 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/SoftDeleteTrigger.cs @@ -1,20 +1,19 @@ -namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers +namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers; + +public class SoftDeleteTrigger(ApplicationDbContext dbContext) : IBeforeSaveTrigger { - public class SoftDeleteTrigger(ApplicationDbContext dbContext) : IBeforeSaveTrigger - { - public const string IsSoftDeleted = "SoftDeleteTrigger_IsSoftDeleted"; + public const string IsSoftDeleted = "SoftDeleteTrigger_IsSoftDeleted"; - readonly ApplicationDbContext _dbContext = dbContext; + readonly ApplicationDbContext _dbContext = dbContext; - public void BeforeSave(ITriggerContext context) + public void BeforeSave(ITriggerContext context) + { + if (context.ChangeType is ChangeType.Deleted) { - if (context.ChangeType is ChangeType.Deleted) - { - context.Items[IsSoftDeleted] = true; - context.Entity.DeletedOn = DateTime.UtcNow; + context.Items[IsSoftDeleted] = true; + context.Entity.DeletedOn = DateTime.UtcNow; - _dbContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; - } + _dbContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; } } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs index 48f6d19..8ae75d7 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/Triggers/StampModifiedOnTrigger.cs @@ -1,15 +1,14 @@ -namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers +namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags.Triggers; + +public class StampModifiedOnTrigger : IBeforeSaveTrigger { - public class StampModifiedOnTrigger : IBeforeSaveTrigger + public void BeforeSave(ITriggerContext context) { - public void BeforeSave(ITriggerContext context) + if (context.ChangeType is ChangeType.Modified) { - if (context.ChangeType is ChangeType.Modified) + if (!context.Items.ContainsKey(SoftDeleteTrigger.IsSoftDeleted)) { - if (!context.Items.ContainsKey(SoftDeleteTrigger.IsSoftDeleted)) - { - context.Entity.ModifiedOn = DateTime.UtcNow; - } + context.Entity.ModifiedOn = DateTime.UtcNow; } } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/User.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/User.cs index 92e6509..ba10ca0 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/User.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityBags/User.cs @@ -1,11 +1,10 @@ -namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags +namespace EntityFrameworkCore.Triggered.IntegrationTests.EntityBags; + +public class User { - public class User - { - public int Id { get; set; } - public string Name { get; set; } + public int Id { get; set; } + public string Name { get; set; } - public DateTime? ModifiedOn { get; set; } - public DateTime? DeletedOn { get; set; } - } + public DateTime? ModifiedOn { get; set; } + public DateTime? DeletedOn { get; set; } } \ No newline at end of file diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/ApplicationDbContext.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/ApplicationDbContext.cs index 6a99aee..fd66026 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/ApplicationDbContext.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/ApplicationDbContext.cs @@ -1,9 +1,8 @@ using Microsoft.EntityFrameworkCore; -namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests +namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests; + +public class ApplicationDbContext(DbContextOptions options) : DbContext(options) { - public class ApplicationDbContext(DbContextOptions options) : DbContext(options) - { - public DbSet Users { get; set; } - } + public DbSet Users { get; set; } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/TriggerLifetimeTestScenario.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/TriggerLifetimeTestScenario.cs index 326cc2c..82bef93 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/TriggerLifetimeTestScenario.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/TriggerLifetimeTestScenario.cs @@ -3,57 +3,56 @@ using ScenarioTests; using Xunit; -namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests +namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests; + +public partial class TriggerLifetimeTestScenario { - public partial class TriggerLifetimeTestScenario - { - public int SingletonTriggerInstances { get; set; } - public int ScopedTriggerInstances { get; set; } - public int TransientTriggerInstances { get; set; } + public int SingletonTriggerInstances { get; set; } + public int ScopedTriggerInstances { get; set; } + public int TransientTriggerInstances { get; set; } - [Scenario(NamingPolicy = ScenarioTestMethodNamingPolicy.Test)] - public void Scenario(ScenarioContext scenario) + [Scenario(NamingPolicy = ScenarioTestMethodNamingPolicy.Test)] + public void Scenario(ScenarioContext scenario) + { + const int iterations = 5; + const int usersPerIteration = 5; + + using var serviceProvider = new ServiceCollection() + .AddDbContext(options => { + options.UseInMemoryDatabase(scenario.TargetName); + options.UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(ServiceLifetime.Singleton); + triggerOptions.AddTrigger(ServiceLifetime.Scoped); + triggerOptions.AddTrigger(); + }); + }) + .AddSingleton(this) + .BuildServiceProvider(); + + for (var iteration = 0; iteration < iterations; iteration++) { - const int iterations = 5; - const int usersPerIteration = 5; - - using var serviceProvider = new ServiceCollection() - .AddDbContext(options => { - options.UseInMemoryDatabase(scenario.TargetName); - options.UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(ServiceLifetime.Singleton); - triggerOptions.AddTrigger(ServiceLifetime.Scoped); - triggerOptions.AddTrigger(); - }); - }) - .AddSingleton(this) - .BuildServiceProvider(); - - for (var iteration = 0; iteration < iterations; iteration++) - { - using var serviceScope = serviceProvider.CreateScope(); - - var dbContext = serviceScope.ServiceProvider.GetRequiredService(); + using var serviceScope = serviceProvider.CreateScope(); - for (var i = 0; i < usersPerIteration; i++) - { - dbContext.Users.Add(new User { }); - } + var dbContext = serviceScope.ServiceProvider.GetRequiredService(); - dbContext.SaveChanges(); + for (var i = 0; i < usersPerIteration; i++) + { + dbContext.Users.Add(new User { }); } - scenario.Fact("1: There is only 1 singleton trigger instance", () => { - Assert.Equal(1, SingletonTriggerInstances); - }); + dbContext.SaveChanges(); + } + + scenario.Fact("1: There is only 1 singleton trigger instance", () => { + Assert.Equal(1, SingletonTriggerInstances); + }); - scenario.Fact("2: There are 5 scoped trigger instances", () => { - Assert.Equal(5, ScopedTriggerInstances); - }); + scenario.Fact("2: There are 5 scoped trigger instances", () => { + Assert.Equal(5, ScopedTriggerInstances); + }); - scenario.Fact("3: There are 25 transient trigger instances", () => { - Assert.Equal(25, TransientTriggerInstances); - }); - } + scenario.Fact("3: There are 25 transient trigger instances", () => { + Assert.Equal(25, TransientTriggerInstances); + }); } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/ScopedTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/ScopedTrigger.cs index 5c8a9f9..2998b77 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/ScopedTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/ScopedTrigger.cs @@ -1,12 +1,11 @@ -namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users +namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users; + +class ScopedTrigger : IBeforeSaveTrigger { - class ScopedTrigger : IBeforeSaveTrigger + public ScopedTrigger(TriggerLifetimeTestScenario triggerLifetimeTestScenario) { - public ScopedTrigger(TriggerLifetimeTestScenario triggerLifetimeTestScenario) - { - triggerLifetimeTestScenario.ScopedTriggerInstances++; - } - - public void BeforeSave(ITriggerContext context) { } + triggerLifetimeTestScenario.ScopedTriggerInstances++; } + + public void BeforeSave(ITriggerContext context) { } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/SingletonTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/SingletonTrigger.cs index cb0f9e9..4acd551 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/SingletonTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/SingletonTrigger.cs @@ -1,13 +1,12 @@ -namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users -{ +namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users; - class SingletonTrigger : IBeforeSaveTrigger - { - public SingletonTrigger(TriggerLifetimeTestScenario triggerLifetimeTestScenario) - { - triggerLifetimeTestScenario.SingletonTriggerInstances++; - } - public void BeforeSave(ITriggerContext context) { } +class SingletonTrigger : IBeforeSaveTrigger +{ + public SingletonTrigger(TriggerLifetimeTestScenario triggerLifetimeTestScenario) + { + triggerLifetimeTestScenario.SingletonTriggerInstances++; } + + public void BeforeSave(ITriggerContext context) { } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/TransientTrigger.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/TransientTrigger.cs index 6fdb342..99c9ea2 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/TransientTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/Triggers/Users/TransientTrigger.cs @@ -1,12 +1,11 @@ -namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users +namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests.Triggers.Users; + +class TransientTrigger : IBeforeSaveTrigger { - class TransientTrigger : IBeforeSaveTrigger + public TransientTrigger(TriggerLifetimeTestScenario triggerLifetimeTestScenario) { - public TransientTrigger(TriggerLifetimeTestScenario triggerLifetimeTestScenario) - { - triggerLifetimeTestScenario.TransientTriggerInstances++; - } - - public void BeforeSave(ITriggerContext context) { } + triggerLifetimeTestScenario.TransientTriggerInstances++; } + + public void BeforeSave(ITriggerContext context) { } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/User.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/User.cs index 0ed034b..9e33709 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/User.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/LifetimeTests/User.cs @@ -1,7 +1,6 @@ -namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests +namespace EntityFrameworkCore.Triggered.IntegrationTests.LifetimeTests; + +public class User { - public class User - { - public int Id { get; set; } - } + public int Id { get; set; } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/ApplicationDbContext.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/ApplicationDbContext.cs index b764892..fc4a3b7 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/ApplicationDbContext.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/ApplicationDbContext.cs @@ -1,20 +1,19 @@ using EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Models; using Microsoft.EntityFrameworkCore; -namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore -{ - public class ApplicationDbContext(string databaseName) : DbContext - { - readonly string _databaseName = databaseName; +namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore; - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseInMemoryDatabase(_databaseName); - optionsBuilder.UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(); - }); - } +public class ApplicationDbContext(string databaseName) : DbContext +{ + readonly string _databaseName = databaseName; - public DbSet Users { get; set; } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseInMemoryDatabase(_databaseName); + optionsBuilder.UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(); + }); } + + public DbSet Users { get; set; } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Models/User.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Models/User.cs index 9884363..3131eb2 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Models/User.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Models/User.cs @@ -1,11 +1,10 @@ -namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Models +namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Models; + +public class User { - public class User - { - public int Id { get; set; } + public int Id { get; set; } - public string UserName { get; set; } + public string UserName { get; set; } - public DateTime? DeletedDate { get; set; } - } + public DateTime? DeletedDate { get; set; } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/TestScenario.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/TestScenario.cs index 2bd7790..365192c 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/TestScenario.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/TestScenario.cs @@ -2,61 +2,60 @@ using ScenarioTests; using Xunit; -namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore +namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore; + +public partial class TestScenario { - public partial class TestScenario + [Scenario(NamingPolicy = ScenarioTestMethodNamingPolicy.Test)] + public void TestScenario1(ScenarioContext scenario) { - [Scenario(NamingPolicy = ScenarioTestMethodNamingPolicy.Test)] - public void TestScenario1(ScenarioContext scenario) - { - const int sampleUsersCount = 100; + const int sampleUsersCount = 100; - var dbContext = new ApplicationDbContext(scenario.TargetName); + var dbContext = new ApplicationDbContext(scenario.TargetName); - // step 1: Populate database with users - dbContext.Users.AddRange(Enumerable.Range(0, sampleUsersCount).Select(x => new User { - UserName = $"user{x}" - })); + // step 1: Populate database with users + dbContext.Users.AddRange(Enumerable.Range(0, sampleUsersCount).Select(x => new User { + UserName = $"user{x}" + })); - dbContext.SaveChanges(); + dbContext.SaveChanges(); - scenario.Fact("Database saved all users", () => { - var usersCount = dbContext.Users.Count(); - Assert.Equal(sampleUsersCount, usersCount); - }); + scenario.Fact("Database saved all users", () => { + var usersCount = dbContext.Users.Count(); + Assert.Equal(sampleUsersCount, usersCount); + }); - // step 2: Delete the last 50 users - dbContext.RemoveRange( - dbContext.Users.Where(x => x.Id > sampleUsersCount / 2) - ); + // step 2: Delete the last 50 users + dbContext.RemoveRange( + dbContext.Users.Where(x => x.Id > sampleUsersCount / 2) + ); - dbContext.SaveChanges(); + dbContext.SaveChanges(); - scenario.Fact("We should still have all our users", () => { - var usersCount = dbContext.Users.Count(); - Assert.Equal(sampleUsersCount, usersCount); - }); + scenario.Fact("We should still have all our users", () => { + var usersCount = dbContext.Users.Count(); + Assert.Equal(sampleUsersCount, usersCount); + }); - scenario.Fact("However, half of them will have been soft deleted", () => { - var usersCount = dbContext.Users.Where(x => x.DeletedDate != null).Count(); - Assert.Equal(sampleUsersCount / 2, usersCount); - }); + scenario.Fact("However, half of them will have been soft deleted", () => { + var usersCount = dbContext.Users.Where(x => x.DeletedDate != null).Count(); + Assert.Equal(sampleUsersCount / 2, usersCount); + }); - // step 3: Undo deletion of our users + // step 3: Undo deletion of our users + { + var users = dbContext.Users.Where(x => x.DeletedDate != null); + foreach (var user in users) { - var users = dbContext.Users.Where(x => x.DeletedDate != null); - foreach (var user in users) - { - user.DeletedDate = null; - } - - dbContext.SaveChanges(); + user.DeletedDate = null; } - scenario.Fact("Ensure that all users are restored", () => { - var usersCount = dbContext.Users.Where(x => x.DeletedDate != null).Count(); - Assert.Equal(0, usersCount); - }); + dbContext.SaveChanges(); } + + scenario.Fact("Ensure that all users are restored", () => { + var usersCount = dbContext.Users.Where(x => x.DeletedDate != null).Count(); + Assert.Equal(0, usersCount); + }); } } diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs index 4d990b3..daa78bb 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/SampleStore/Triggers/Users/SoftDeleteUsers.cs @@ -1,19 +1,18 @@ using EntityFrameworkCore.Triggered.Extensions; using EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Models; -namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Triggers.Users +namespace EntityFrameworkCore.Triggered.IntegrationTests.SampleStore.Triggers.Users; + +public class SoftDeleteUsers(ApplicationDbContext applicationDbContext) : Trigger { - public class SoftDeleteUsers(ApplicationDbContext applicationDbContext) : Trigger - { - readonly ApplicationDbContext _applicationDbContext = applicationDbContext; + readonly ApplicationDbContext _applicationDbContext = applicationDbContext; - public override void BeforeSave(ITriggerContext context) + public override void BeforeSave(ITriggerContext context) + { + if (context.ChangeType is ChangeType.Deleted) { - if (context.ChangeType is ChangeType.Deleted) - { - _applicationDbContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; - context.Entity.DeletedDate = DateTime.UtcNow; - } + _applicationDbContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; + context.Entity.DeletedDate = DateTime.UtcNow; } } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs b/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs index 78c49e0..bc2ddbe 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/EFCore5DbContextTests.cs @@ -6,171 +6,170 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests +namespace EntityFrameworkCore.Triggered.Tests; + +public class EFCoreDbContextTests { - public class EFCoreDbContextTests + public class TestModel { - public class TestModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } + public Guid Id { get; set; } + public string Name { get; set; } + } + + class TestDbContext(bool stubService = true) : DbContext + { + readonly bool _stubService = stubService; + + public TriggerStub TriggerStub { get; } = new TriggerStub(); + + public DbSet TestModels { get; set; } - class TestDbContext(bool stubService = true) : DbContext + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - readonly bool _stubService = stubService; + base.OnConfiguring(optionsBuilder); - public TriggerStub TriggerStub { get; } = new TriggerStub(); + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); - public DbSet TestModels { get; set; } + optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.EnableServiceProviderCaching(false); + optionsBuilder.UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(TriggerStub); + }); - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + if (_stubService) { - base.OnConfiguring(optionsBuilder); - - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - - optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.EnableServiceProviderCaching(false); - optionsBuilder.UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(TriggerStub); - }); - - if (_stubService) - { - optionsBuilder.ReplaceService(); - } + optionsBuilder.ReplaceService(); } + } - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity().HasKey(x => x.Id); + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().HasKey(x => x.Id); - base.OnModelCreating(modelBuilder); - } + base.OnModelCreating(modelBuilder); } + } - TestDbContext CreateSubject(bool stubService = true) - => new(stubService); + TestDbContext CreateSubject(bool stubService = true) + => new(stubService); - [Fact] - public void SaveChanges_CreatesTriggerrSession() - { - var subject = CreateSubject(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + [Fact] + public void SaveChanges_CreatesTriggerrSession() + { + var subject = CreateSubject(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - subject.SaveChanges(); - Assert.Equal(1, triggerServiceStub.CreateSessionCalls); - } + subject.SaveChanges(); + Assert.Equal(1, triggerServiceStub.CreateSessionCalls); + } - [Fact] - public void SaveChangesWithAccept_CreatesTriggerSession() - { - var subject = CreateSubject(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + [Fact] + public void SaveChangesWithAccept_CreatesTriggerSession() + { + var subject = CreateSubject(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - subject.SaveChanges(true); - Assert.Equal(1, triggerServiceStub.CreateSessionCalls); - } + subject.SaveChanges(true); + Assert.Equal(1, triggerServiceStub.CreateSessionCalls); + } - [Fact] - public async Task SaveChangesAsync_CreatesTriggerSession() - { - var subject = CreateSubject(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + [Fact] + public async Task SaveChangesAsync_CreatesTriggerSession() + { + var subject = CreateSubject(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - await subject.SaveChangesAsync(); - Assert.Equal(1, triggerServiceStub.CreateSessionCalls); - } + await subject.SaveChangesAsync(); + Assert.Equal(1, triggerServiceStub.CreateSessionCalls); + } - [Fact] - public void SaveChanges_ExplicitTriggerSession_ReturnsActiveTriggerSession() - { - var subject = CreateSubject(true); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + [Fact] + public void SaveChanges_ExplicitTriggerSession_ReturnsActiveTriggerSession() + { + var subject = CreateSubject(true); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - using var triggerSession = subject.CreateTriggerSession(); + using var triggerSession = subject.CreateTriggerSession(); - subject.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + subject.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - subject.SaveChanges(); + subject.SaveChanges(); - Assert.Equal(1, triggerServiceStub.CreateSessionCalls); - } + Assert.Equal(1, triggerServiceStub.CreateSessionCalls); + } - [Fact] - public void SaveChanges_CascadingCall_ReturnsActiveTriggerSession() - { - var subject = CreateSubject(false); - - subject.TriggerStub.BeforeSaveHandler = _ => { - if (subject.TriggerStub.BeforeSaveInvocations.Count <= 1) - { - subject.SaveChanges(); - } - }; - - subject.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + [Fact] + public void SaveChanges_CascadingCall_ReturnsActiveTriggerSession() + { + var subject = CreateSubject(false); - subject.SaveChanges(); + subject.TriggerStub.BeforeSaveHandler = _ => { + if (subject.TriggerStub.BeforeSaveInvocations.Count <= 1) + { + subject.SaveChanges(); + } + }; - Assert.Single(subject.TriggerStub.BeforeSaveInvocations); - } + subject.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - [Fact] - public async Task SaveChangesAsyncWithAccept_CreatesChangeHandlerSession() - { - var subject = CreateSubject(); - var triggerSessionStub = (TriggerServiceStub)subject.GetService(); + subject.SaveChanges(); - await subject.SaveChangesAsync(true); - Assert.Equal(1, triggerSessionStub.CreateSessionCalls); - } + Assert.Single(subject.TriggerStub.BeforeSaveInvocations); + } - [Fact] - public async Task SaveChangesAsync_CascadingCall_ReturnsActiveTriggerSession() - { - var subject = CreateSubject(false); - - subject.TriggerStub.BeforeSaveAsyncHandler = async (_, _) => { - if (subject.TriggerStub.BeforeSaveInvocations.Count <= 1) - { - await subject.SaveChangesAsync(); - } - }; - - subject.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + [Fact] + public async Task SaveChangesAsyncWithAccept_CreatesChangeHandlerSession() + { + var subject = CreateSubject(); + var triggerSessionStub = (TriggerServiceStub)subject.GetService(); - await subject.SaveChangesAsync(); + await subject.SaveChangesAsync(true); + Assert.Equal(1, triggerSessionStub.CreateSessionCalls); + } - Assert.Single(subject.TriggerStub.BeforeSaveInvocations); - } + [Fact] + public async Task SaveChangesAsync_CascadingCall_ReturnsActiveTriggerSession() + { + var subject = CreateSubject(false); - [Fact] - public void SetTriggerServiceProvider_CallsCapturedChanges() - { - var subject = new TestDbContext(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + subject.TriggerStub.BeforeSaveAsyncHandler = async (_, _) => { + if (subject.TriggerStub.BeforeSaveInvocations.Count <= 1) + { + await subject.SaveChangesAsync(); + } + }; - subject.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + subject.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - subject.SaveChanges(); + await subject.SaveChangesAsync(); - Assert.Equal(1, triggerServiceStub.LastSession.CaptureDiscoveredChangesCalls); - } + Assert.Single(subject.TriggerStub.BeforeSaveInvocations); + } + + [Fact] + public void SetTriggerServiceProvider_CallsCapturedChanges() + { + var subject = new TestDbContext(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + + subject.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); + + subject.SaveChanges(); + + Assert.Equal(1, triggerServiceStub.LastSession.CaptureDiscoveredChangesCalls); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs index 68e3b2c..19210b1 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Extensions/DbContextExtensionTests.cs @@ -4,145 +4,144 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Extensions +namespace EntityFrameworkCore.Triggered.Tests.Extensions; + +public class DbContextExtensionTests { - public class DbContextExtensionTests - { - class TestModel { public int Id { get; set; } public string Name { get; set; } } + class TestModel { public int Id { get; set; } public string Name { get; set; } } - class SampleTrigger : IBeforeSaveTrigger - { - public int BeforeSaveCalls { get; set; } + class SampleTrigger : IBeforeSaveTrigger + { + public int BeforeSaveCalls { get; set; } - public void BeforeSave(ITriggerContext context) => BeforeSaveCalls += 1; - } + public void BeforeSave(ITriggerContext context) => BeforeSaveCalls += 1; + } - class TestDbContext : DbContext - { - public bool UseTriggers { get; set; } = true; + class TestDbContext : DbContext + { + public bool UseTriggers { get; set; } = true; - public DbSet TestModels { get; set; } + public DbSet TestModels { get; set; } - public SampleTrigger SampleTrigger { get; } = new(); + public SampleTrigger SampleTrigger { get; } = new(); - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseInMemoryDatabase("test"); + if (UseTriggers) { - optionsBuilder.UseInMemoryDatabase("test"); - if (UseTriggers) - { - optionsBuilder.UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(SampleTrigger); - }); - } - - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + optionsBuilder.UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(SampleTrigger); }); } + + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); } + } - [Fact] - public void GetTriggerService_ValidDbContext_ReturnsSession() - { - using var context = new TestDbContext(); + [Fact] + public void GetTriggerService_ValidDbContext_ReturnsSession() + { + using var context = new TestDbContext(); - var triggerService = DbContextExtensions.GetTriggerService(context); + var triggerService = DbContextExtensions.GetTriggerService(context); - Assert.NotNull(triggerService); - } + Assert.NotNull(triggerService); + } - [Fact] - public void GetTriggerService_NonTriggeredDbContext_ReturnsSession() - { - using var context = new TestDbContext { UseTriggers = false }; + [Fact] + public void GetTriggerService_NonTriggeredDbContext_ReturnsSession() + { + using var context = new TestDbContext { UseTriggers = false }; - Assert.Throws(() => - DbContextExtensions.GetTriggerService(context)); - } + Assert.Throws(() => + DbContextExtensions.GetTriggerService(context)); + } - [Fact] - public void CreateTriggerSession_ValidDbContext_CreatesNewSession() - { - using var context = new TestDbContext(); - var triggerSession = DbContextExtensions.CreateTriggerSession(context); + [Fact] + public void CreateTriggerSession_ValidDbContext_CreatesNewSession() + { + using var context = new TestDbContext(); + var triggerSession = DbContextExtensions.CreateTriggerSession(context); - Assert.NotNull(triggerSession); - Assert.NotNull(context.GetService()?.Current); - } + Assert.NotNull(triggerSession); + Assert.NotNull(context.GetService()?.Current); + } - [Fact] - public void SaveChangesWithoutTriggers_DoesNotRaiseTrigger() - { - // arrange - using var context = new TestDbContext(); - context.TestModels.Add(new TestModel { }); + [Fact] + public void SaveChangesWithoutTriggers_DoesNotRaiseTrigger() + { + // arrange + using var context = new TestDbContext(); + context.TestModels.Add(new TestModel { }); - // act - context.SaveChangesWithoutTriggers(); + // act + context.SaveChangesWithoutTriggers(); - // assert - Assert.Equal(0, context.SampleTrigger.BeforeSaveCalls); - } + // assert + Assert.Equal(0, context.SampleTrigger.BeforeSaveCalls); + } - [Fact] - public void SaveChangesWithoutTriggers_RestoresConfiguration() - { - // arrange - using var context = new TestDbContext(); - context.TestModels.Add(new TestModel { }); - var expectedConfiguration = context.GetTriggerService().Configuration; + [Fact] + public void SaveChangesWithoutTriggers_RestoresConfiguration() + { + // arrange + using var context = new TestDbContext(); + context.TestModels.Add(new TestModel { }); + var expectedConfiguration = context.GetTriggerService().Configuration; - // act - context.SaveChangesWithoutTriggers(); + // act + context.SaveChangesWithoutTriggers(); - // assert - Assert.Same(expectedConfiguration, context.GetTriggerService().Configuration); - } + // assert + Assert.Same(expectedConfiguration, context.GetTriggerService().Configuration); + } - [Fact] - public async Task SaveChangesAsyncWithoutTriggers_DoesNotRaiseTrigger() - { - // arrange - using var context = new TestDbContext(); - context.TestModels.Add(new TestModel { }); + [Fact] + public async Task SaveChangesAsyncWithoutTriggers_DoesNotRaiseTrigger() + { + // arrange + using var context = new TestDbContext(); + context.TestModels.Add(new TestModel { }); - // act - await context.SaveChangesWithoutTriggersAsync(); + // act + await context.SaveChangesWithoutTriggersAsync(); - // assert - Assert.Equal(0, context.SampleTrigger.BeforeSaveCalls); - } + // assert + Assert.Equal(0, context.SampleTrigger.BeforeSaveCalls); + } - [Fact] - public async Task SaveChangesAsyncWithoutTriggers_RestoresConfiguration() - { - // arrange - using var context = new TestDbContext(); - context.TestModels.Add(new TestModel { }); - var expectedConfiguration = context.GetTriggerService().Configuration; + [Fact] + public async Task SaveChangesAsyncWithoutTriggers_RestoresConfiguration() + { + // arrange + using var context = new TestDbContext(); + context.TestModels.Add(new TestModel { }); + var expectedConfiguration = context.GetTriggerService().Configuration; - // act - await context.SaveChangesWithoutTriggersAsync(); + // act + await context.SaveChangesWithoutTriggersAsync(); - // assert - Assert.Same(expectedConfiguration, context.GetTriggerService().Configuration); - } + // assert + Assert.Same(expectedConfiguration, context.GetTriggerService().Configuration); + } - [Fact] - public void CreateNewTriggerSession_ExistingSession_Throws() - { - // arrange - using var context = new TestDbContext(); - context.TestModels.Add(new TestModel { }); - context.CreateNewTriggerSession(); - - // act - Assert.Throws(() => - context.CreateNewTriggerSession()); - } + [Fact] + public void CreateNewTriggerSession_ExistingSession_Throws() + { + // arrange + using var context = new TestDbContext(); + context.TestModels.Add(new TestModel { }); + context.CreateNewTriggerSession(); + + // act + Assert.Throws(() => + context.CreateNewTriggerSession()); + } - } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs index ae80064..1ee7df3 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/ServiceCollectionExtensionsTests.cs @@ -6,235 +6,234 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Infrastructure +namespace EntityFrameworkCore.Triggered.Tests.Infrastructure; + +public class ServiceCollectionExtensionsTests { - public class ServiceCollectionExtensionsTests + class TestModel { public int Id { get; set; } } + class TestDbContext(DbContextOptions options) : DbContext(options) + { + + public DbSet TestModels { get; set; } + } + + class TestDbContextFactory(IServiceProvider serviceProvider, DbContextOptions options, IDbContextFactorySource factorySource) : DbContextFactory(serviceProvider, options, factorySource) + { + } + + [Fact] + public void AddTriggeredDbContext_AddsTriggersAndCallsUsersAction() { - class TestModel { public int Id { get; set; } } - class TestDbContext(DbContextOptions options) : DbContext(options) - { - - public DbSet TestModels { get; set; } - } - - class TestDbContextFactory(IServiceProvider serviceProvider, DbContextOptions options, IDbContextFactorySource factorySource) : DbContextFactory(serviceProvider, options, factorySource) - { - } - - [Fact] - public void AddTriggeredDbContext_AddsTriggersAndCallsUsersAction() - { - var subject = new ServiceCollection(); - var optionsActionsCalled = false; - subject.AddTriggeredDbContext(options => { - optionsActionsCalled = true; - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); + var subject = new ServiceCollection(); + var optionsActionsCalled = false; + subject.AddTriggeredDbContext(options => { + optionsActionsCalled = true; + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); }); + }); - var serviceProvider = subject.BuildServiceProvider(); - var context = serviceProvider.GetRequiredService(); - - Assert.True(optionsActionsCalled); - Assert.NotNull(context.GetService()); - } - - [Fact] - public void AddTriggeredDbContextPool_AddsTriggersAndCallsUsersAction() - { - var subject = new ServiceCollection(); - var optionsActionsCalled = false; - subject.AddTriggeredDbContext(options => { - optionsActionsCalled = true; - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); + var serviceProvider = subject.BuildServiceProvider(); + var context = serviceProvider.GetRequiredService(); + + Assert.True(optionsActionsCalled); + Assert.NotNull(context.GetService()); + } + + [Fact] + public void AddTriggeredDbContextPool_AddsTriggersAndCallsUsersAction() + { + var subject = new ServiceCollection(); + var optionsActionsCalled = false; + subject.AddTriggeredDbContext(options => { + optionsActionsCalled = true; + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); }); + }); - var serviceProvider = subject.BuildServiceProvider(); - var context = serviceProvider.GetRequiredService(); + var serviceProvider = subject.BuildServiceProvider(); + var context = serviceProvider.GetRequiredService(); - Assert.True(optionsActionsCalled); - Assert.NotNull(context.GetService()); - } + Assert.True(optionsActionsCalled); + Assert.NotNull(context.GetService()); + } - [Fact] - public void AddTriggeredDbContext_ReusesScopedServiceProvider() - { - var subject = new ServiceCollection(); - subject.AddTriggeredDbContext(options => { - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }).AddScoped, TriggerStub>(); + [Fact] + public void AddTriggeredDbContext_ReusesScopedServiceProvider() + { + var subject = new ServiceCollection(); + subject.AddTriggeredDbContext(options => { + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }).AddScoped, TriggerStub>(); - var serviceProvider = subject.BuildServiceProvider(); + var serviceProvider = subject.BuildServiceProvider(); - using var scope = serviceProvider.CreateScope(); + using var scope = serviceProvider.CreateScope(); - var context = scope.ServiceProvider.GetRequiredService(); - context.TestModels.Add(new TestModel()); + var context = scope.ServiceProvider.GetRequiredService(); + context.TestModels.Add(new TestModel()); - context.SaveChanges(); + context.SaveChanges(); - var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; - Assert.NotNull(triggerStub); - Assert.Single(triggerStub.BeforeSaveInvocations); - } + var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; + Assert.NotNull(triggerStub); + Assert.Single(triggerStub.BeforeSaveInvocations); + } - [Fact] - public void AddTriggeredDbContextPool_ReusesScopedServiceProvider() - { - var subject = new ServiceCollection(); - subject.AddTriggeredDbContextPool(options => { - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }).AddScoped, TriggerStub>(); + [Fact] + public void AddTriggeredDbContextPool_ReusesScopedServiceProvider() + { + var subject = new ServiceCollection(); + subject.AddTriggeredDbContextPool(options => { + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }).AddScoped, TriggerStub>(); - var serviceProvider = subject.BuildServiceProvider(); + var serviceProvider = subject.BuildServiceProvider(); - using var scope = serviceProvider.CreateScope(); + using var scope = serviceProvider.CreateScope(); - var context = scope.ServiceProvider.GetRequiredService(); - context.TestModels.Add(new TestModel()); + var context = scope.ServiceProvider.GetRequiredService(); + context.TestModels.Add(new TestModel()); - context.SaveChanges(); + context.SaveChanges(); - var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; - Assert.NotNull(triggerStub); - Assert.Single(triggerStub.BeforeSaveInvocations); - } + var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; + Assert.NotNull(triggerStub); + Assert.Single(triggerStub.BeforeSaveInvocations); + } - [Fact] - public void AddTriggeredDbContextPool_SupportsAScopedLifetime() - { - var subject = new ServiceCollection(); - subject.AddTriggeredDbContextPool(options => { - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); + [Fact] + public void AddTriggeredDbContextPool_SupportsAScopedLifetime() + { + var subject = new ServiceCollection(); + subject.AddTriggeredDbContextPool(options => { + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); }); + }); - var serviceProvider = subject.BuildServiceProvider(); + var serviceProvider = subject.BuildServiceProvider(); - using var scope = serviceProvider.CreateScope(); + using var scope = serviceProvider.CreateScope(); - var context1 = scope.ServiceProvider.GetRequiredService(); - var context2 = scope.ServiceProvider.GetRequiredService(); + var context1 = scope.ServiceProvider.GetRequiredService(); + var context2 = scope.ServiceProvider.GetRequiredService(); - Assert.Equal(context1, context1); - } + Assert.Equal(context1, context1); + } - [Fact] - public void AddTriggeredDbContextPool_SupportAContractType() - { - var subject = new ServiceCollection(); - subject.AddTriggeredDbContextPool(options => { - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); + [Fact] + public void AddTriggeredDbContextPool_SupportAContractType() + { + var subject = new ServiceCollection(); + subject.AddTriggeredDbContextPool(options => { + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); }); + }); - var serviceProvider = subject.BuildServiceProvider(); + var serviceProvider = subject.BuildServiceProvider(); - using var scope = serviceProvider.CreateScope(); + using var scope = serviceProvider.CreateScope(); - var context1 = scope.ServiceProvider.GetRequiredService(); - var context2 = scope.ServiceProvider.GetRequiredService(); + var context1 = scope.ServiceProvider.GetRequiredService(); + var context2 = scope.ServiceProvider.GetRequiredService(); - Assert.Equal(context1, context1); - } + Assert.Equal(context1, context1); + } - [Fact] - public void AddTriggeredDbContextFactory_ReusesScopedServiceProvider() - { - var subject = new ServiceCollection(); - subject.AddTriggeredDbContextFactory(options => { - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }).AddScoped, TriggerStub>(); + [Fact] + public void AddTriggeredDbContextFactory_ReusesScopedServiceProvider() + { + var subject = new ServiceCollection(); + subject.AddTriggeredDbContextFactory(options => { + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }).AddScoped, TriggerStub>(); - var serviceProvider = subject.BuildServiceProvider(); + var serviceProvider = subject.BuildServiceProvider(); - using var scope = serviceProvider.CreateScope(); + using var scope = serviceProvider.CreateScope(); - var contextFactory = scope.ServiceProvider.GetRequiredService>(); - var context = contextFactory.CreateDbContext(); + var contextFactory = scope.ServiceProvider.GetRequiredService>(); + var context = contextFactory.CreateDbContext(); - context.TestModels.Add(new TestModel()); + context.TestModels.Add(new TestModel()); - context.SaveChanges(); + context.SaveChanges(); - var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; - Assert.NotNull(triggerStub); - Assert.Single(triggerStub.BeforeSaveInvocations); - } + var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; + Assert.NotNull(triggerStub); + Assert.Single(triggerStub.BeforeSaveInvocations); + } - [Fact] - public void AddTriggeredDbContextFactory_WithCustomFactory_ReusesScopedServiceProvider() - { - var subject = new ServiceCollection(); - subject.AddTriggeredDbContextFactory(options => { - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }).AddScoped, TriggerStub>(); + [Fact] + public void AddTriggeredDbContextFactory_WithCustomFactory_ReusesScopedServiceProvider() + { + var subject = new ServiceCollection(); + subject.AddTriggeredDbContextFactory(options => { + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }).AddScoped, TriggerStub>(); - var serviceProvider = subject.BuildServiceProvider(); + var serviceProvider = subject.BuildServiceProvider(); - using var scope = serviceProvider.CreateScope(); + using var scope = serviceProvider.CreateScope(); - var contextFactory = scope.ServiceProvider.GetRequiredService>(); + var contextFactory = scope.ServiceProvider.GetRequiredService>(); - var context = contextFactory.CreateDbContext(); + var context = contextFactory.CreateDbContext(); - context.TestModels.Add(new TestModel()); + context.TestModels.Add(new TestModel()); - context.SaveChanges(); + context.SaveChanges(); - var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; - Assert.NotNull(triggerStub); - Assert.Single(triggerStub.BeforeSaveInvocations); - } + var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; + Assert.NotNull(triggerStub); + Assert.Single(triggerStub.BeforeSaveInvocations); + } - [Fact] - public void AddTriggeredPooledDbContextFactory_ReusesScopedServiceProvider() - { - var subject = new ServiceCollection(); - subject.AddTriggeredPooledDbContextFactory(options => { - options.UseInMemoryDatabase("test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }).AddScoped, TriggerStub>(); + [Fact] + public void AddTriggeredPooledDbContextFactory_ReusesScopedServiceProvider() + { + var subject = new ServiceCollection(); + subject.AddTriggeredPooledDbContextFactory(options => { + options.UseInMemoryDatabase("test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }).AddScoped, TriggerStub>(); - var serviceProvider = subject.BuildServiceProvider(); + var serviceProvider = subject.BuildServiceProvider(); - using var scope = serviceProvider.CreateScope(); + using var scope = serviceProvider.CreateScope(); - var contextFactory = scope.ServiceProvider.GetRequiredService>(); - var context = contextFactory.CreateDbContext(); + var contextFactory = scope.ServiceProvider.GetRequiredService>(); + var context = contextFactory.CreateDbContext(); - context.TestModels.Add(new TestModel()); + context.TestModels.Add(new TestModel()); - context.SaveChanges(); + context.SaveChanges(); - var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; - Assert.NotNull(triggerStub); - Assert.Single(triggerStub.BeforeSaveInvocations); - } + var triggerStub = scope.ServiceProvider.GetRequiredService>() as TriggerStub; + Assert.NotNull(triggerStub); + Assert.Single(triggerStub.BeforeSaveInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/TriggersContextOptionsBuilderTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/TriggersContextOptionsBuilderTests.cs index 3deff3d..1442a21 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/TriggersContextOptionsBuilderTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Infrastructure/TriggersContextOptionsBuilderTests.cs @@ -3,47 +3,46 @@ using Microsoft.EntityFrameworkCore; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Infrastructure +namespace EntityFrameworkCore.Triggered.Tests.Infrastructure; + +public class TriggersContextOptionsBuilderTests { - public class TriggersContextOptionsBuilderTests + static (TriggersContextOptionsBuilder subject, Func extensionAccessor) CreateSubject() { - static (TriggersContextOptionsBuilder subject, Func extensionAccessor) CreateSubject() - { - var optionsBuilder = new DbContextOptionsBuilder(); - TriggersContextOptionsBuilder subject = null; - optionsBuilder.UseTriggers(x => subject = x); + var optionsBuilder = new DbContextOptionsBuilder(); + TriggersContextOptionsBuilder subject = null; + optionsBuilder.UseTriggers(x => subject = x); - return (subject, () => optionsBuilder.Options.FindExtension()); - } + return (subject, () => optionsBuilder.Options.FindExtension()); + } - [Fact] - public void CascadingMode_Sticks() - { - var (subject, extensionAccessor) = CreateSubject(); + [Fact] + public void CascadingMode_Sticks() + { + var (subject, extensionAccessor) = CreateSubject(); - subject.CascadeBehavior(CascadeBehavior.None); + subject.CascadeBehavior(CascadeBehavior.None); - Assert.Equal(CascadeBehavior.None, extensionAccessor().CascadeBehavior); - } + Assert.Equal(CascadeBehavior.None, extensionAccessor().CascadeBehavior); + } - [Fact] - public void MaxCascadingCycles_Sticks() - { - var (subject, extensionAccessor) = CreateSubject(); + [Fact] + public void MaxCascadingCycles_Sticks() + { + var (subject, extensionAccessor) = CreateSubject(); - subject.MaxCascadeCycles(10); + subject.MaxCascadeCycles(10); - Assert.Equal(10, extensionAccessor().MaxCascadeCycles); - } + Assert.Equal(10, extensionAccessor().MaxCascadeCycles); + } - [Fact] - public void AddTigger_Sticks() - { - var (subject, extensionAccessor) = CreateSubject(); + [Fact] + public void AddTigger_Sticks() + { + var (subject, extensionAccessor) = CreateSubject(); - subject.AddTrigger>(); + subject.AddTrigger>(); - Assert.Single(extensionAccessor().Triggers); - } + Assert.Single(extensionAccessor().Triggers); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/ApplicationTriggerServiceProviderAccessorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/ApplicationTriggerServiceProviderAccessorTests.cs index 9f8e216..6a57b54 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/ApplicationTriggerServiceProviderAccessorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/ApplicationTriggerServiceProviderAccessorTests.cs @@ -6,84 +6,83 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class ApplicationTriggerServiceProviderAccessorTests { - public class ApplicationTriggerServiceProviderAccessorTests + class TestDbContext : DbContext { - class TestDbContext : DbContext + public TestDbContext() { - public TestDbContext() - { - } + } - public TestDbContext(DbContextOptions options) : base(options) - { - } + public TestDbContext(DbContextOptions options) : base(options) + { + } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - base.OnConfiguring(optionsBuilder); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); - optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.UseTriggers(triggerOptions => { - triggerOptions.AddTrigger>(); - }); + optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.UseTriggers(triggerOptions => { + triggerOptions.AddTrigger>(); + }); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - } + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); } + } - [Fact] - public void GetTriggerServiceProvider_WithApplicationDiAndTransform_ReturnsCustomServiceProvider() - { - var applicationServiceProvider = new ServiceCollection() - .AddDbContext(options => { - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - - options.UseInMemoryDatabase("Test") - .UseTriggers(); - }) - .AddScoped() - .BuildServiceProvider(); + [Fact] + public void GetTriggerServiceProvider_WithApplicationDiAndTransform_ReturnsCustomServiceProvider() + { + var applicationServiceProvider = new ServiceCollection() + .AddDbContext(options => { + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); - var dbContext = applicationServiceProvider.GetRequiredService(); + options.UseInMemoryDatabase("Test") + .UseTriggers(); + }) + .AddScoped() + .BuildServiceProvider(); - var subject = new ApplicationTriggerServiceProviderAccessor(dbContext.GetInfrastructure(), _ => applicationServiceProvider); - var triggerServiceProvider = subject.GetTriggerServiceProvider(); + var dbContext = applicationServiceProvider.GetRequiredService(); - Assert.Equal(applicationServiceProvider, triggerServiceProvider); - } + var subject = new ApplicationTriggerServiceProviderAccessor(dbContext.GetInfrastructure(), _ => applicationServiceProvider); + var triggerServiceProvider = subject.GetTriggerServiceProvider(); - [Fact] - public void GetTriggerServiceProvider_WithExplicitlySetServiceProvider_ReturnsSetServiceProvider() - { - var applicationServiceProvider = new ServiceCollection() - .AddDbContext(options => { - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); + Assert.Equal(applicationServiceProvider, triggerServiceProvider); + } - options.UseInMemoryDatabase("Test") - .UseTriggers(); - }) - .AddScoped() - .BuildServiceProvider(); + [Fact] + public void GetTriggerServiceProvider_WithExplicitlySetServiceProvider_ReturnsSetServiceProvider() + { + var applicationServiceProvider = new ServiceCollection() + .AddDbContext(options => { + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); - var internalServiceProviderStub = new ServiceCollection().BuildServiceProvider(); + options.UseInMemoryDatabase("Test") + .UseTriggers(); + }) + .AddScoped() + .BuildServiceProvider(); - var subject = applicationServiceProvider.GetRequiredService().GetService(); - subject.SetTriggerServiceProvider(applicationServiceProvider); + var internalServiceProviderStub = new ServiceCollection().BuildServiceProvider(); - var triggerServiceProvider = subject.GetTriggerServiceProvider(); + var subject = applicationServiceProvider.GetRequiredService().GetService(); + subject.SetTriggerServiceProvider(applicationServiceProvider); - Assert.Equal(applicationServiceProvider, triggerServiceProvider); - } + var triggerServiceProvider = subject.GetTriggerServiceProvider(); + Assert.Equal(applicationServiceProvider, triggerServiceProvider); } + } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/EntityAndTypeRecursionStrategyTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/EntityAndTypeRecursionStrategyTests.cs index c4edc50..d6ba5c5 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/EntityAndTypeRecursionStrategyTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/EntityAndTypeRecursionStrategyTests.cs @@ -1,15 +1,14 @@ using EntityFrameworkCore.Triggered.Internal.CascadeStrategies; -namespace EntityFrameworkCore.Triggered.Tests.Internal.CascadingStrategies +namespace EntityFrameworkCore.Triggered.Tests.Internal.CascadingStrategies; + +public class EntityAndTypeCascadingStrategyTests : CascadingStrategyTestsBase { - public class EntityAndTypeCascadingStrategyTests : CascadingStrategyTestsBase - { - protected override bool CanCascadeUnmodifiedExpectedOutcome => false; - protected override bool CanCascadeModifiedExpectedOutcome => false; - protected override bool CanCascadeUnmodifiedDifferentTypeExpectedOutcome => true; - protected override bool CanCascadeModifiedDifferentTypeExpectedOutcome => true; + protected override bool CanCascadeUnmodifiedExpectedOutcome => false; + protected override bool CanCascadeModifiedExpectedOutcome => false; + protected override bool CanCascadeUnmodifiedDifferentTypeExpectedOutcome => true; + protected override bool CanCascadeModifiedDifferentTypeExpectedOutcome => true; - protected override ICascadeStrategy CreateSubject() - => new NoCascadeStrategy(); - } + protected override ICascadeStrategy CreateSubject() + => new NoCascadeStrategy(); } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/NoRecursionStrategyTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/NoRecursionStrategyTests.cs index 211036c..f1e9a7d 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/NoRecursionStrategyTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/NoRecursionStrategyTests.cs @@ -1,15 +1,14 @@ using EntityFrameworkCore.Triggered.Internal.CascadeStrategies; -namespace EntityFrameworkCore.Triggered.Tests.Internal.CascadingStrategies +namespace EntityFrameworkCore.Triggered.Tests.Internal.CascadingStrategies; + +public class NoCascadingStrategyTests : CascadingStrategyTestsBase { - public class NoCascadingStrategyTests : CascadingStrategyTestsBase - { - protected override bool CanCascadeUnmodifiedExpectedOutcome => false; - protected override bool CanCascadeModifiedExpectedOutcome => false; - protected override bool CanCascadeUnmodifiedDifferentTypeExpectedOutcome => false; - protected override bool CanCascadeModifiedDifferentTypeExpectedOutcome => false; + protected override bool CanCascadeUnmodifiedExpectedOutcome => false; + protected override bool CanCascadeModifiedExpectedOutcome => false; + protected override bool CanCascadeUnmodifiedDifferentTypeExpectedOutcome => false; + protected override bool CanCascadeModifiedDifferentTypeExpectedOutcome => false; - protected override ICascadeStrategy CreateSubject() - => new NoCascadeStrategy(); - } + protected override ICascadeStrategy CreateSubject() + => new NoCascadeStrategy(); } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/RecursionStrategyTestsBase.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/RecursionStrategyTestsBase.cs index 7eb7fba..83897f1 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/RecursionStrategyTestsBase.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingStrategies/RecursionStrategyTestsBase.cs @@ -3,87 +3,86 @@ using Microsoft.EntityFrameworkCore; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal.CascadeStrategies +namespace EntityFrameworkCore.Triggered.Tests.Internal.CascadeStrategies; + +public abstract class CascadeStrategyTestsBase { - public abstract class CascadeStrategyTestsBase + class TestModel { public int Id { get; set; } public int Property1 { get; set; } } + + class TestDbContext : DbContext { - class TestModel { public int Id { get; set; } public int Property1 { get; set; } } + public DbSet TestModels { get; set; } - class TestDbContext : DbContext + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - public DbSet TestModels { get; set; } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.EnableServiceProviderCaching(false); - } + optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.EnableServiceProviderCaching(false); } + } - protected abstract ICascadeStrategy CreateSubject(); + protected abstract ICascadeStrategy CreateSubject(); - protected abstract bool CanCascadeUnmodifiedExpectedOutcome { get; } - protected abstract bool CanCascadeModifiedExpectedOutcome { get; } - protected abstract bool CanCascadeUnmodifiedDifferentTypeExpectedOutcome { get; } - protected abstract bool CanCascadeModifiedDifferentTypeExpectedOutcome { get; } + protected abstract bool CanCascadeUnmodifiedExpectedOutcome { get; } + protected abstract bool CanCascadeModifiedExpectedOutcome { get; } + protected abstract bool CanCascadeUnmodifiedDifferentTypeExpectedOutcome { get; } + protected abstract bool CanCascadeModifiedDifferentTypeExpectedOutcome { get; } - [Fact] - public void CanCascade_Unmodified() - { - using var dbContext = new TestDbContext(); - var subject = CreateSubject(); - var entity = new TestModel { Property1 = 1 }; - dbContext.Add(entity); - var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); + [Fact] + public void CanCascade_Unmodified() + { + using var dbContext = new TestDbContext(); + var subject = CreateSubject(); + var entity = new TestModel { Property1 = 1 }; + dbContext.Add(entity); + var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); - var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Added, previousTriggerContextDescriptor); + var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Added, previousTriggerContextDescriptor); - Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); - } + Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); + } - [Fact] - public void CanCascade_Modified() - { - using var dbContext = new TestDbContext(); - var subject = CreateSubject(); - var entity = new TestModel { Property1 = 1 }; - dbContext.Add(entity); - var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); + [Fact] + public void CanCascade_Modified() + { + using var dbContext = new TestDbContext(); + var subject = CreateSubject(); + var entity = new TestModel { Property1 = 1 }; + dbContext.Add(entity); + var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); - entity.Property1 = 2; - var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Added, previousTriggerContextDescriptor); + entity.Property1 = 2; + var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Added, previousTriggerContextDescriptor); - Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); - } + Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); + } - [Fact] - public void CanCascade_UnmodifiedDifferentType() - { - using var dbContext = new TestDbContext(); - var subject = CreateSubject(); - var entity = new TestModel { Property1 = 1 }; - dbContext.Add(entity); - var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); + [Fact] + public void CanCascade_UnmodifiedDifferentType() + { + using var dbContext = new TestDbContext(); + var subject = CreateSubject(); + var entity = new TestModel { Property1 = 1 }; + dbContext.Add(entity); + var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); - var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor); + var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor); - Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); - } + Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); + } - [Fact] - public void CanCascade_ModifiedDifferentType() - { - using var dbContext = new TestDbContext(); - var subject = CreateSubject(); - var entity = new TestModel { Property1 = 1 }; - dbContext.Add(entity); - var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); + [Fact] + public void CanCascade_ModifiedDifferentType() + { + using var dbContext = new TestDbContext(); + var subject = CreateSubject(); + var entity = new TestModel { Property1 = 1 }; + dbContext.Add(entity); + var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); - entity.Property1 = 2; - var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor); + entity.Property1 = 2; + var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor); - Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); - } + Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingTriggerContextDiscoveryStrategyTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingTriggerContextDiscoveryStrategyTests.cs index 53b8b74..b8693f8 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingTriggerContextDiscoveryStrategyTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/CascadingTriggerContextDiscoveryStrategyTests.cs @@ -5,56 +5,55 @@ using Microsoft.Extensions.Logging.Abstractions; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class CascadeTriggerContextDiscoveryStrategyTests { - public class CascadeTriggerContextDiscoveryStrategyTests + class TestModel + { + public Guid Id { get; set; } + public string Name { get; set; } + } + + class TestDbContext : DbContext { - class TestModel + public TestDbContext(DbContextOptions options) : base(options) { - public Guid Id { get; set; } - public string Name { get; set; } } - class TestDbContext : DbContext + public TestDbContext() { - public TestDbContext(DbContextOptions options) : base(options) - { - } - - public TestDbContext() - { - } - - public DbSet TestModels { get; set; } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - base.OnConfiguring(optionsBuilder); - - optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.UseTriggers(); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - } } + public DbSet TestModels { get; set; } - [Fact] - public void DiscoverChanges_MultipleCalls_ReturnsDeltaOfChanges() + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - using var dbContext = new TestDbContext(); - var subject = new CascadingTriggerContextDiscoveryStrategy("test", false); - var triggerContextTracker = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - triggerContextTracker.DiscoverChanges().Count(); - var initialContextDescriptors = subject.Discover(new(false, 100), triggerContextTracker, new NullLogger()).ToList(); + base.OnConfiguring(optionsBuilder); - dbContext.Add(new TestModel { }); + optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.UseTriggers(); + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + } + } - var contextDescriptors = subject.Discover(new(false, 100), triggerContextTracker, new NullLogger()).ToList(); - Assert.NotEqual(initialContextDescriptors, contextDescriptors); - } + [Fact] + public void DiscoverChanges_MultipleCalls_ReturnsDeltaOfChanges() + { + using var dbContext = new TestDbContext(); + var subject = new CascadingTriggerContextDiscoveryStrategy("test", false); + var triggerContextTracker = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + triggerContextTracker.DiscoverChanges().Count(); + var initialContextDescriptors = subject.Discover(new(false, 100), triggerContextTracker, new NullLogger()).ToList(); + + dbContext.Add(new TestModel { }); + var contextDescriptors = subject.Discover(new(false, 100), triggerContextTracker, new NullLogger()).ToList(); + + Assert.NotEqual(initialContextDescriptors, contextDescriptors); } + } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveAsyncTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveAsyncTriggerDescriptorTests.cs index 2569b14..9b61a0a 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveAsyncTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveAsyncTriggerDescriptorTests.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors; + +public class AfterSaveAsyncTriggerDescriptorTests { - public class AfterSaveAsyncTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new AfterSaveAsyncTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new AfterSaveAsyncTriggerDescriptor(entityType); - Assert.Equal(typeof(IAfterSaveAsyncTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IAfterSaveAsyncTrigger), subject.TriggerType); + } - [Fact] - public async Task Execute_ForwardsCall() - { - var entityType = typeof(string); - var triggerStub = new TriggerStub(); - var subject = new AfterSaveAsyncTriggerDescriptor(entityType); + [Fact] + public async Task Execute_ForwardsCall() + { + var entityType = typeof(string); + var triggerStub = new TriggerStub(); + var subject = new AfterSaveAsyncTriggerDescriptor(entityType); - await subject.Invoke(triggerStub, new TriggerContextStub(), null, default); + await subject.Invoke(triggerStub, new TriggerContextStub(), null, default); - Assert.Single(triggerStub.AfterSaveAsyncInvocations); - } + Assert.Single(triggerStub.AfterSaveAsyncInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptorTests.cs index 40981a8..9fbe560 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedAsyncTriggerDescriptorTests.cs @@ -2,31 +2,30 @@ using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors; + +public class AfterSaveFailedAsyncTriggerDescriptorTests { - public class AfterSaveFailedAsyncTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new AfterSaveFailedAsyncTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new AfterSaveFailedAsyncTriggerDescriptor(entityType); - Assert.Equal(typeof(IAfterSaveFailedAsyncTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IAfterSaveFailedAsyncTrigger), subject.TriggerType); + } - [Fact] - public async Task Execute_ForwardsCall() - { - var entityType = typeof(string); - var exception = new Exception(); - var triggerStub = new TriggerStub(); - var subject = new AfterSaveFailedAsyncTriggerDescriptor(entityType); + [Fact] + public async Task Execute_ForwardsCall() + { + var entityType = typeof(string); + var exception = new Exception(); + var triggerStub = new TriggerStub(); + var subject = new AfterSaveFailedAsyncTriggerDescriptor(entityType); - await subject.Invoke(triggerStub, new TriggerContextStub(), exception, default); + await subject.Invoke(triggerStub, new TriggerContextStub(), exception, default); - Assert.Single(triggerStub.AfterSaveFailedAsyncInvocations); - Assert.Equal(exception, triggerStub.AfterSaveFailedAsyncInvocations.First().exception); - } + Assert.Single(triggerStub.AfterSaveFailedAsyncInvocations); + Assert.Equal(exception, triggerStub.AfterSaveFailedAsyncInvocations.First().exception); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs index 29128ce..3b4a6c9 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveFailedTriggerDescriptorTests.cs @@ -2,31 +2,30 @@ using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors; + +public class AfterSaveFailedTriggerDescriptorTests { - public class AfterSaveFailedTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new AfterSaveFailedTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new AfterSaveFailedTriggerDescriptor(entityType); - Assert.Equal(typeof(IAfterSaveFailedTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IAfterSaveFailedTrigger), subject.TriggerType); + } - [Fact] - public void Execute_ForwardsCall() - { - var entityType = typeof(string); - var exception = new Exception(); - var triggerStub = new TriggerStub(); - var subject = new AfterSaveFailedTriggerDescriptor(entityType); + [Fact] + public void Execute_ForwardsCall() + { + var entityType = typeof(string); + var exception = new Exception(); + var triggerStub = new TriggerStub(); + var subject = new AfterSaveFailedTriggerDescriptor(entityType); - subject.Invoke(triggerStub, new TriggerContextStub(), exception); + subject.Invoke(triggerStub, new TriggerContextStub(), exception); - Assert.Single(triggerStub.AfterSaveFailedInvocations); - Assert.Equal(exception, triggerStub.AfterSaveFailedInvocations.First().exception); - } + Assert.Single(triggerStub.AfterSaveFailedInvocations); + Assert.Equal(exception, triggerStub.AfterSaveFailedInvocations.First().exception); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveTriggerDescriptorTests.cs index b7583b9..94dc72a 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/AfterSaveTriggerDescriptorTests.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors; + +public class AfterSaveTriggerDescriptorTests { - public class AfterSaveTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new AfterSaveTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new AfterSaveTriggerDescriptor(entityType); - Assert.Equal(typeof(IAfterSaveTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IAfterSaveTrigger), subject.TriggerType); + } - [Fact] - public void Execute_ForwardsCall() - { - var entityType = typeof(string); - var triggerStub = new TriggerStub(); - var subject = new AfterSaveTriggerDescriptor(entityType); + [Fact] + public void Execute_ForwardsCall() + { + var entityType = typeof(string); + var triggerStub = new TriggerStub(); + var subject = new AfterSaveTriggerDescriptor(entityType); - subject.Invoke(triggerStub, new TriggerContextStub(), null); + subject.Invoke(triggerStub, new TriggerContextStub(), null); - Assert.Single(triggerStub.AfterSaveInvocations); - } + Assert.Single(triggerStub.AfterSaveInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptorTests.cs index 4e3e9d3..9c99013 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveAsyncTriggerDescriptorTests.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors; + +public class BeforeSaveAsyncTriggerDescriptorTests { - public class BeforeSaveAsyncTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new BeforeSaveAsyncTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new BeforeSaveAsyncTriggerDescriptor(entityType); - Assert.Equal(typeof(IBeforeSaveAsyncTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IBeforeSaveAsyncTrigger), subject.TriggerType); + } - [Fact] - public async Task Invoke_ForwardsCall() - { - var entityType = typeof(string); - var triggerStub = new TriggerStub(); - var subject = new BeforeSaveAsyncTriggerDescriptor(entityType); + [Fact] + public async Task Invoke_ForwardsCall() + { + var entityType = typeof(string); + var triggerStub = new TriggerStub(); + var subject = new BeforeSaveAsyncTriggerDescriptor(entityType); - await subject.Invoke(triggerStub, new TriggerContextStub(), null, default); + await subject.Invoke(triggerStub, new TriggerContextStub(), null, default); - Assert.Single(triggerStub.BeforeSaveAsyncInvocations); - } + Assert.Single(triggerStub.BeforeSaveAsyncInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveTriggerDescriptorTests.cs index cb31da8..32d4b1f 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/Descriptors/BeforeSaveTriggerDescriptorTests.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors +namespace EntityFrameworkCore.Triggered.Tests.Internal.Descriptors; + +public class BeforeSaveTriggerDescriptorTests { - public class BeforeSaveTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new BeforeSaveTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new BeforeSaveTriggerDescriptor(entityType); - Assert.Equal(typeof(IBeforeSaveTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IBeforeSaveTrigger), subject.TriggerType); + } - [Fact] - public void Invoke_ForwardsCall() - { - var entityType = typeof(string); - var triggerStub = new TriggerStub(); - var subject = new BeforeSaveTriggerDescriptor(entityType); + [Fact] + public void Invoke_ForwardsCall() + { + var entityType = typeof(string); + var triggerStub = new TriggerStub(); + var subject = new BeforeSaveTriggerDescriptor(entityType); - subject.Invoke(triggerStub, new TriggerContextStub(), null); + subject.Invoke(triggerStub, new TriggerContextStub(), null); - Assert.Single(triggerStub.BeforeSaveInvocations); - } + Assert.Single(triggerStub.BeforeSaveInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/EntityBagStateManagerTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/EntityBagStateManagerTests.cs index 1045f32..78d4b9d 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/EntityBagStateManagerTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/EntityBagStateManagerTests.cs @@ -1,33 +1,32 @@ using EntityFrameworkCore.Triggered.Internal; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class EntityBagStateManagerTests { - public class EntityBagStateManagerTests + [Fact] + public void GetForEntity_MultipleCallsForSameEntity_ReturnsSameInstance() { - [Fact] - public void GetForEntity_MultipleCallsForSameEntity_ReturnsSameInstance() - { - var subject = new EntityBagStateManager(); - var entity = new object(); - var expectedBag = subject.GetForEntity(entity); + var subject = new EntityBagStateManager(); + var entity = new object(); + var expectedBag = subject.GetForEntity(entity); - var bag = subject.GetForEntity(entity); + var bag = subject.GetForEntity(entity); - Assert.Same(expectedBag, bag); - } + Assert.Same(expectedBag, bag); + } - [Fact] - public void GetForEntity_MultipleCallsForDifferentEntities_ReturnsDifferentInstances() - { - var subject = new EntityBagStateManager(); - var entity1 = new object(); - var entity2 = new object(); + [Fact] + public void GetForEntity_MultipleCallsForDifferentEntities_ReturnsDifferentInstances() + { + var subject = new EntityBagStateManager(); + var entity1 = new object(); + var entity2 = new object(); - var entity1Bag = subject.GetForEntity(entity1); - var entity2Bag = subject.GetForEntity(entity2); + var entity1Bag = subject.GetForEntity(entity1); + var entity2Bag = subject.GetForEntity(entity2); - Assert.NotSame(entity1Bag, entity2Bag); - } + Assert.NotSame(entity1Bag, entity2Bag); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/HybridServiceProviderTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/HybridServiceProviderTests.cs index cd67167..da6e678 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/HybridServiceProviderTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/HybridServiceProviderTests.cs @@ -4,66 +4,65 @@ using ScenarioTests; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public partial class HybridServiceProviderTests { - public partial class HybridServiceProviderTests + class CustomDbContext : DbContext { - class CustomDbContext : DbContext - { - } + } - class ConcreteCustomDbContext : CustomDbContext - { + class ConcreteCustomDbContext : CustomDbContext + { - } + } - [Scenario] - public void ScenarioTests(ScenarioContext scenario) - { - var dbContext = new ConcreteCustomDbContext(); - var serviceProvider = new ServiceCollection() - .AddSingleton("X") - .BuildServiceProvider(); + [Scenario] + public void ScenarioTests(ScenarioContext scenario) + { + var dbContext = new ConcreteCustomDbContext(); + var serviceProvider = new ServiceCollection() + .AddSingleton("X") + .BuildServiceProvider(); - var subject = new HybridServiceProvider(serviceProvider, dbContext); + var subject = new HybridServiceProvider(serviceProvider, dbContext); - scenario.Fact("Can retrieve DbContext from ServiceProvider", () => { - var result = subject.GetService(); - Assert.NotNull(result); - }); + scenario.Fact("Can retrieve DbContext from ServiceProvider", () => { + var result = subject.GetService(); + Assert.NotNull(result); + }); - scenario.Fact("Can retrieve CustomDbContext from ServiceProvider", () => { - var result = subject.GetService(); - Assert.NotNull(result); - }); + scenario.Fact("Can retrieve CustomDbContext from ServiceProvider", () => { + var result = subject.GetService(); + Assert.NotNull(result); + }); - scenario.Fact("Can retrieve ConcreteCustomDbContext from ServiceProvider", () => { - var result = subject.GetService(); - Assert.NotNull(result); - }); + scenario.Fact("Can retrieve ConcreteCustomDbContext from ServiceProvider", () => { + var result = subject.GetService(); + Assert.NotNull(result); + }); - scenario.Fact("Can retrieve custom service from ServiceProvider", () => { - var result = subject.GetService(); - Assert.NotNull(result); - }); - } + scenario.Fact("Can retrieve custom service from ServiceProvider", () => { + var result = subject.GetService(); + Assert.NotNull(result); + }); + } - [Fact] - public void CantOverrideDbContext() - { - var dbContext1 = new ConcreteCustomDbContext(); - var dbContext2 = new ConcreteCustomDbContext(); + [Fact] + public void CantOverrideDbContext() + { + var dbContext1 = new ConcreteCustomDbContext(); + var dbContext2 = new ConcreteCustomDbContext(); - var serviceProvider = new ServiceCollection() - .AddSingleton(dbContext2) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddSingleton(dbContext2) + .BuildServiceProvider(); - var subject = new HybridServiceProvider(serviceProvider, dbContext1); + var subject = new HybridServiceProvider(serviceProvider, dbContext1); - var result = subject.GetRequiredService(); + var result = subject.GetRequiredService(); - Assert.Equal(dbContext1, result); - } + Assert.Equal(dbContext1, result); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/NonCascadingTriggerContextDiscoveryStrategyTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/NonCascadingTriggerContextDiscoveryStrategyTests.cs index 538a1eb..61ccbf7 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/NonCascadingTriggerContextDiscoveryStrategyTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/NonCascadingTriggerContextDiscoveryStrategyTests.cs @@ -5,50 +5,49 @@ using Microsoft.Extensions.Logging.Abstractions; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class NonCascadingTriggerContextDiscoveryStrategyTests { - public class NonCascadingTriggerContextDiscoveryStrategyTests + class TestModel { - class TestModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } + public Guid Id { get; set; } + public string Name { get; set; } + } - class TestDbContext : DbContext - { - public DbSet TestModels { get; set; } + class TestDbContext : DbContext + { + public DbSet TestModels { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - base.OnConfiguring(optionsBuilder); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); - optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.UseTriggers(triggerOptions => { - }); + optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.UseTriggers(triggerOptions => { + }); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - } + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); } + } - [Fact] - public void DiscoverChanges_MultipleCalls_ReturnsSameResult() - { - using var dbContext = new TestDbContext(); - var subject = new NonCascadingTriggerContextDiscoveryStrategy("test"); - var triggerContextTracker = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - triggerContextTracker.DiscoverChanges().Count(); - var initialContextDescriptors = subject.Discover(new(false, 0), triggerContextTracker, new NullLogger()).ToList(); + [Fact] + public void DiscoverChanges_MultipleCalls_ReturnsSameResult() + { + using var dbContext = new TestDbContext(); + var subject = new NonCascadingTriggerContextDiscoveryStrategy("test"); + var triggerContextTracker = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + triggerContextTracker.DiscoverChanges().Count(); + var initialContextDescriptors = subject.Discover(new(false, 0), triggerContextTracker, new NullLogger()).ToList(); - dbContext.Add(new TestModel { }); + dbContext.Add(new TestModel { }); - var contextDescriptors = subject.Discover(new(false, 0), triggerContextTracker, new NullLogger()).ToList(); + var contextDescriptors = subject.Discover(new(false, 0), triggerContextTracker, new NullLogger()).ToList(); - Assert.Equal(initialContextDescriptors, contextDescriptors); - } + Assert.Equal(initialContextDescriptors, contextDescriptors); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/RecursionStrategies/RecursionStrategyTestsBase.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/RecursionStrategies/RecursionStrategyTestsBase.cs index 3ed2b21..a67e848 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/RecursionStrategies/RecursionStrategyTestsBase.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/RecursionStrategies/RecursionStrategyTestsBase.cs @@ -4,89 +4,88 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal.CascadingStrategies +namespace EntityFrameworkCore.Triggered.Tests.Internal.CascadingStrategies; + +public abstract class CascadingStrategyTestsBase { - public abstract class CascadingStrategyTestsBase + class TestModel { public int Id { get; set; } public int Property1 { get; set; } } + + class TestDbContext : DbContext { - class TestModel { public int Id { get; set; } public int Property1 { get; set; } } + public DbSet TestModels { get; set; } - class TestDbContext : DbContext + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - public DbSet TestModels { get; set; } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - } + optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); } + } - protected abstract ICascadeStrategy CreateSubject(); + protected abstract ICascadeStrategy CreateSubject(); - protected abstract bool CanCascadeUnmodifiedExpectedOutcome { get; } - protected abstract bool CanCascadeModifiedExpectedOutcome { get; } - protected abstract bool CanCascadeUnmodifiedDifferentTypeExpectedOutcome { get; } - protected abstract bool CanCascadeModifiedDifferentTypeExpectedOutcome { get; } + protected abstract bool CanCascadeUnmodifiedExpectedOutcome { get; } + protected abstract bool CanCascadeModifiedExpectedOutcome { get; } + protected abstract bool CanCascadeUnmodifiedDifferentTypeExpectedOutcome { get; } + protected abstract bool CanCascadeModifiedDifferentTypeExpectedOutcome { get; } - [Fact] - public void CanCascade_Unmodified() - { - using var dbContext = new TestDbContext(); - var subject = CreateSubject(); - var entity = new TestModel { Property1 = 1 }; - dbContext.Add(entity); - var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); + [Fact] + public void CanCascade_Unmodified() + { + using var dbContext = new TestDbContext(); + var subject = CreateSubject(); + var entity = new TestModel { Property1 = 1 }; + dbContext.Add(entity); + var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); - var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Added, previousTriggerContextDescriptor); + var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Added, previousTriggerContextDescriptor); - Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); - } + Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); + } - [Fact] - public void CanCascade_Modified() - { - using var dbContext = new TestDbContext(); - var subject = CreateSubject(); - var entity = new TestModel { Property1 = 1 }; - dbContext.Add(entity); - var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); + [Fact] + public void CanCascade_Modified() + { + using var dbContext = new TestDbContext(); + var subject = CreateSubject(); + var entity = new TestModel { Property1 = 1 }; + dbContext.Add(entity); + var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); - entity.Property1 = 2; - var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Added, previousTriggerContextDescriptor); + entity.Property1 = 2; + var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Added, previousTriggerContextDescriptor); - Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); - } + Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); + } - [Fact] - public void CanCascade_UnmodifiedDifferentType() - { - using var dbContext = new TestDbContext(); - var subject = CreateSubject(); - var entity = new TestModel { Property1 = 1 }; - dbContext.Add(entity); - var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); + [Fact] + public void CanCascade_UnmodifiedDifferentType() + { + using var dbContext = new TestDbContext(); + var subject = CreateSubject(); + var entity = new TestModel { Property1 = 1 }; + dbContext.Add(entity); + var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); - var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor); + var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor); - Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); - } + Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); + } - [Fact] - public void CanCascade_ModifiedDifferentType() - { - using var dbContext = new TestDbContext(); - var subject = CreateSubject(); - var entity = new TestModel { Property1 = 1 }; - dbContext.Add(entity); - var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); + [Fact] + public void CanCascade_ModifiedDifferentType() + { + using var dbContext = new TestDbContext(); + var subject = CreateSubject(); + var entity = new TestModel { Property1 = 1 }; + dbContext.Add(entity); + var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); - entity.Property1 = 2; - var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor); + entity.Property1 = 2; + var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor); - Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); - } + Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextFactoryTests.cs index ed57214..8066262 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextFactoryTests.cs @@ -3,40 +3,39 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerContextFactoryTests { - public class TriggerContextFactoryTests + class TestModel { - class TestModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } + public Guid Id { get; set; } + public string Name { get; set; } + } - class TestDbContext : DbContext - { - public DbSet TestModels { get; set; } + class TestDbContext : DbContext + { + public DbSet TestModels { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - base.OnConfiguring(optionsBuilder); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); - optionsBuilder.UseInMemoryDatabase(nameof(TriggerContextFactoryTests)); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - } + optionsBuilder.UseInMemoryDatabase(nameof(TriggerContextFactoryTests)); + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); } + } - [Fact] - public void Activate_ReturnsInstance() - { - using var dbContext = new TestDbContext(); - var entityEntry = dbContext.Entry(new TestModel { }); + [Fact] + public void Activate_ReturnsInstance() + { + using var dbContext = new TestDbContext(); + var entityEntry = dbContext.Entry(new TestModel { }); - var result = TriggerContextFactory.Activate(entityEntry, entityEntry.OriginalValues, ChangeType.Added, new()); + var result = TriggerContextFactory.Activate(entityEntry, entityEntry.OriginalValues, ChangeType.Added, new()); - Assert.NotNull(result); - } + Assert.NotNull(result); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextTrackerTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextTrackerTests.cs index 409ad1d..6349113 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextTrackerTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerContextTrackerTests.cs @@ -4,176 +4,175 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerContextTrackerTests { - public class TriggerContextTrackerTests + class TestModel { - class TestModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } + public Guid Id { get; set; } + public string Name { get; set; } + } - class TestDbContext : DbContext - { - public DbSet TestModels { get; set; } + class TestDbContext : DbContext + { + public DbSet TestModels { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - base.OnConfiguring(optionsBuilder); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); - optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - } + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); } + } - [Fact] - public void DiscoverChanges_AddedEntity_CreatesDescriptor() - { - using var dbContext = new TestDbContext(); - var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + [Fact] + public void DiscoverChanges_AddedEntity_CreatesDescriptor() + { + using var dbContext = new TestDbContext(); + var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - dbContext.Entry(new TestModel { }).State = EntityState.Added; + dbContext.Entry(new TestModel { }).State = EntityState.Added; - var triggerContextDescriptor = subject.DiscoverChanges().FirstOrDefault(); + var triggerContextDescriptor = subject.DiscoverChanges().FirstOrDefault(); - Assert.Equal(ChangeType.Added, triggerContextDescriptor.ChangeType); - } + Assert.Equal(ChangeType.Added, triggerContextDescriptor.ChangeType); + } - [Fact] - public void DiscoverChanges_ModifiedEntity_CreatesDescriptor() - { - using var dbContext = new TestDbContext(); - var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + [Fact] + public void DiscoverChanges_ModifiedEntity_CreatesDescriptor() + { + using var dbContext = new TestDbContext(); + var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - dbContext.Entry(new TestModel { }).State = EntityState.Modified; + dbContext.Entry(new TestModel { }).State = EntityState.Modified; - var triggerContextDescriptor = subject.DiscoverChanges().FirstOrDefault(); + var triggerContextDescriptor = subject.DiscoverChanges().FirstOrDefault(); - Assert.Equal(ChangeType.Modified, triggerContextDescriptor.ChangeType); - } + Assert.Equal(ChangeType.Modified, triggerContextDescriptor.ChangeType); + } - [Fact] - public void DiscoverChanges_DeletedEntity_CreatesDescriptor() - { - using var dbContext = new TestDbContext(); - var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + [Fact] + public void DiscoverChanges_DeletedEntity_CreatesDescriptor() + { + using var dbContext = new TestDbContext(); + var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - dbContext.Entry(new TestModel { }).State = EntityState.Deleted; + dbContext.Entry(new TestModel { }).State = EntityState.Deleted; - var triggerContextDescriptor = subject.DiscoverChanges().FirstOrDefault(); + var triggerContextDescriptor = subject.DiscoverChanges().FirstOrDefault(); - Assert.Equal(ChangeType.Deleted, triggerContextDescriptor.ChangeType); - } + Assert.Equal(ChangeType.Deleted, triggerContextDescriptor.ChangeType); + } - [Fact] - public void DiscoveredChanges_NoCallToDiscoverChanges_ReturnsNull() - { - using var dbContext = new TestDbContext(); - var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + [Fact] + public void DiscoveredChanges_NoCallToDiscoverChanges_ReturnsNull() + { + using var dbContext = new TestDbContext(); + var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - var discoveredChanges = subject.DiscoveredChanges; + var discoveredChanges = subject.DiscoveredChanges; - Assert.Null(discoveredChanges); - } + Assert.Null(discoveredChanges); + } - [Fact] - public void DiscoveredChanges_MultipleCallsToDiscoverChanges_ReturnsAllChanges() - { - using var dbContext = new TestDbContext(); - var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + [Fact] + public void DiscoveredChanges_MultipleCallsToDiscoverChanges_ReturnsAllChanges() + { + using var dbContext = new TestDbContext(); + var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - dbContext.Add(new TestModel { }); - subject.DiscoverChanges().Count(); + dbContext.Add(new TestModel { }); + subject.DiscoverChanges().Count(); - dbContext.Add(new TestModel { }); - subject.DiscoverChanges().Count(); + dbContext.Add(new TestModel { }); + subject.DiscoverChanges().Count(); - var discoveredChanges = subject.DiscoveredChanges; + var discoveredChanges = subject.DiscoveredChanges; - Assert.Equal(2, discoveredChanges.Count()); - } + Assert.Equal(2, discoveredChanges.Count()); + } - [Fact] - public void CaptureDiscoveredChangesAfterAdd_UnchangedEntry_RemovesDiscoveredChange() - { - using var dbContext = new TestDbContext(); - var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + [Fact] + public void CaptureDiscoveredChangesAfterAdd_UnchangedEntry_RemovesDiscoveredChange() + { + using var dbContext = new TestDbContext(); + var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - var testModel = new TestModel(); - dbContext.Entry(testModel).State = EntityState.Added; + var testModel = new TestModel(); + dbContext.Entry(testModel).State = EntityState.Added; - var disoveredChanges = subject.DiscoverChanges(); - Assert.Single(disoveredChanges); - Assert.Single(subject.DiscoveredChanges); + var disoveredChanges = subject.DiscoverChanges(); + Assert.Single(disoveredChanges); + Assert.Single(subject.DiscoveredChanges); - dbContext.Entry(testModel).State = EntityState.Unchanged; - disoveredChanges = subject.DiscoverChanges(); - subject.CaptureChanges(); - Assert.Empty(subject.DiscoveredChanges); - } + dbContext.Entry(testModel).State = EntityState.Unchanged; + disoveredChanges = subject.DiscoverChanges(); + subject.CaptureChanges(); + Assert.Empty(subject.DiscoveredChanges); + } - [Fact] - public void CaptureDiscoveredChangesAfterAdd_DetachedEntry_RemovesDiscoveredChange() - { - using var dbContext = new TestDbContext(); - var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + [Fact] + public void CaptureDiscoveredChangesAfterAdd_DetachedEntry_RemovesDiscoveredChange() + { + using var dbContext = new TestDbContext(); + var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - var testModel = new TestModel(); - dbContext.Entry(testModel).State = EntityState.Added; + var testModel = new TestModel(); + dbContext.Entry(testModel).State = EntityState.Added; - var disoveredChanges = subject.DiscoverChanges(); - Assert.Single(disoveredChanges); - Assert.Single(subject.DiscoveredChanges); + var disoveredChanges = subject.DiscoverChanges(); + Assert.Single(disoveredChanges); + Assert.Single(subject.DiscoveredChanges); - dbContext.Entry(testModel).State = EntityState.Detached; - subject.CaptureChanges(); - Assert.Empty(subject.DiscoveredChanges); - } + dbContext.Entry(testModel).State = EntityState.Detached; + subject.CaptureChanges(); + Assert.Empty(subject.DiscoveredChanges); + } - [Fact] - public void CaptureDiscoveredChanges_DeletedEntry_UpdatesDiscoveredChange() - { - using var dbContext = new TestDbContext(); - var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + [Fact] + public void CaptureDiscoveredChanges_DeletedEntry_UpdatesDiscoveredChange() + { + using var dbContext = new TestDbContext(); + var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - var testModel = new TestModel(); - dbContext.Entry(testModel).State = EntityState.Added; + var testModel = new TestModel(); + dbContext.Entry(testModel).State = EntityState.Added; - var disoveredChanges = subject.DiscoverChanges(); - Assert.Single(disoveredChanges); - Assert.Single(subject.DiscoveredChanges); + var disoveredChanges = subject.DiscoverChanges(); + Assert.Single(disoveredChanges); + Assert.Single(subject.DiscoveredChanges); - dbContext.Entry(testModel).State = EntityState.Deleted; - disoveredChanges = subject.DiscoverChanges(); - Assert.Equal(2, subject.DiscoveredChanges.Count()); + dbContext.Entry(testModel).State = EntityState.Deleted; + disoveredChanges = subject.DiscoverChanges(); + Assert.Equal(2, subject.DiscoveredChanges.Count()); - subject.CaptureChanges(); - Assert.Single(subject.DiscoveredChanges); - } + subject.CaptureChanges(); + Assert.Single(subject.DiscoveredChanges); + } - [Fact] - public void UncaptureDiscoveredChanges_OneEntry_RestoresDiscoveredChange() - { - using var dbContext = new TestDbContext(); - var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); + [Fact] + public void UncaptureDiscoveredChanges_OneEntry_RestoresDiscoveredChange() + { + using var dbContext = new TestDbContext(); + var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); - var testModel = new TestModel(); - dbContext.Entry(testModel).State = EntityState.Added; + var testModel = new TestModel(); + dbContext.Entry(testModel).State = EntityState.Added; - var disoveredChanges = subject.DiscoverChanges(); - dbContext.Entry(testModel).State = EntityState.Unchanged; + var disoveredChanges = subject.DiscoverChanges(); + dbContext.Entry(testModel).State = EntityState.Unchanged; - subject.CaptureChanges(); - Assert.Empty(subject.DiscoveredChanges); + subject.CaptureChanges(); + Assert.Empty(subject.DiscoveredChanges); - subject.UncaptureChanges(); - Assert.Single(subject.DiscoveredChanges); - } + subject.UncaptureChanges(); + Assert.Single(subject.DiscoveredChanges); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs index 6e40efb..46421f6 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDescriptorTests.cs @@ -2,34 +2,33 @@ using EntityFrameworkCore.Triggered.Internal.Descriptors; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerDescriptorTests { - public class TriggerDescriptorTests + class TestTriggerWithPriority : IBeforeSaveTrigger, ITriggerPriority { - class TestTriggerWithPriority : IBeforeSaveTrigger, ITriggerPriority - { - public int Priority => 1; + public int Priority => 1; - public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); - } + public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); + } - class TestTriggerWithoutPriority : IBeforeSaveTrigger - { - public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); - } + class TestTriggerWithoutPriority : IBeforeSaveTrigger + { + public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); + } - [Fact] - public void Priority_TriggerWithoutPriority_ReturnsDefault() - { - var subject = new TriggerDescriptor(new BeforeSaveTriggerDescriptor(typeof(object)), new TestTriggerWithoutPriority()); - Assert.Equal(0, subject.Priority); - } + [Fact] + public void Priority_TriggerWithoutPriority_ReturnsDefault() + { + var subject = new TriggerDescriptor(new BeforeSaveTriggerDescriptor(typeof(object)), new TestTriggerWithoutPriority()); + Assert.Equal(0, subject.Priority); + } - [Fact] - public void Priority_TriggerWithPriority_ReturnsPriority() - { - var subject = new TriggerDescriptor(new BeforeSaveTriggerDescriptor(typeof(object)), new TestTriggerWithPriority()); - Assert.Equal(1, subject.Priority); - } + [Fact] + public void Priority_TriggerWithPriority_ReturnsPriority() + { + var subject = new TriggerDescriptor(new BeforeSaveTriggerDescriptor(typeof(object)), new TestTriggerWithPriority()); + Assert.Equal(1, subject.Priority); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs index dbe2306..a2531b7 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerDiscoveryServiceTests.cs @@ -4,162 +4,161 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerDiscoveryServiceTests { - public class TriggerDiscoveryServiceTests + class TriggerServiceProviderAccessor(IServiceProvider serviceProvider) : ITriggerServiceProviderAccessor { - class TriggerServiceProviderAccessor(IServiceProvider serviceProvider) : ITriggerServiceProviderAccessor - { - readonly IServiceProvider _serviceProvider = serviceProvider; + readonly IServiceProvider _serviceProvider = serviceProvider; - public IServiceProvider GetTriggerServiceProvider() => _serviceProvider; - } + public IServiceProvider GetTriggerServiceProvider() => _serviceProvider; + } - [Fact] - public void DiscoverTriggers_ConcreteType_CreatesDescriptor() - { - var serviceProvider = new ServiceCollection() - .AddScoped, TriggerStub>() - .BuildServiceProvider(); + [Fact] + public void DiscoverTriggers_ConcreteType_CreatesDescriptor() + { + var serviceProvider = new ServiceCollection() + .AddScoped, TriggerStub>() + .BuildServiceProvider(); - var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); + var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); - var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); + var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); - Assert.Single(result); - } + Assert.Single(result); + } - [Fact] - public void DiscoverTriggers_BaseType_CreatesDescriptor() - { - var serviceProvider = new ServiceCollection() - .AddScoped, TriggerStub>() - .BuildServiceProvider(); + [Fact] + public void DiscoverTriggers_BaseType_CreatesDescriptor() + { + var serviceProvider = new ServiceCollection() + .AddScoped, TriggerStub>() + .BuildServiceProvider(); - var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); + var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); - var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); + var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); - Assert.Single(result); - } + Assert.Single(result); + } - [Fact] - public void DiscoverChangeHandlerInvocations_InterfaceType_CreatesDescriptor() - { - var serviceProvider = new ServiceCollection() - .AddScoped, TriggerStub>() - .BuildServiceProvider(); + [Fact] + public void DiscoverChangeHandlerInvocations_InterfaceType_CreatesDescriptor() + { + var serviceProvider = new ServiceCollection() + .AddScoped, TriggerStub>() + .BuildServiceProvider(); - var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); + var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); - var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); + var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); - Assert.Single(result); - } + Assert.Single(result); + } - [Fact] - public void DiscoverChangeHandlerInvocations_SortTriggersByInterfaceThenType() - { - var interfaceTrigger = new TriggerStub(); - var typeTrigger = new TriggerStub(); + [Fact] + public void DiscoverChangeHandlerInvocations_SortTriggersByInterfaceThenType() + { + var interfaceTrigger = new TriggerStub(); + var typeTrigger = new TriggerStub(); - var serviceProvider = new ServiceCollection() - .AddSingleton>(typeTrigger) - .AddSingleton>(interfaceTrigger) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddSingleton>(typeTrigger) + .AddSingleton>(interfaceTrigger) + .BuildServiceProvider(); - var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); + var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); - var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); + var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); - Assert.Equal(2, result.Count()); - Assert.Equal(interfaceTrigger, result.First().Trigger); - Assert.Equal(typeTrigger, result.Last().Trigger); - } + Assert.Equal(2, result.Count()); + Assert.Equal(interfaceTrigger, result.First().Trigger); + Assert.Equal(typeTrigger, result.Last().Trigger); + } - [Fact] - public void DiscoverChangeHandlerInvocations_SortTriggersByBaseTypeThenDerivedType() - { - var objectTrigger = new TriggerStub(); - var concreteTrigger = new TriggerStub(); + [Fact] + public void DiscoverChangeHandlerInvocations_SortTriggersByBaseTypeThenDerivedType() + { + var objectTrigger = new TriggerStub(); + var concreteTrigger = new TriggerStub(); - var serviceProvider = new ServiceCollection() - .AddSingleton>(concreteTrigger) - .AddSingleton>(objectTrigger) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddSingleton>(concreteTrigger) + .AddSingleton>(objectTrigger) + .BuildServiceProvider(); - var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); + var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); - var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); + var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); - Assert.Equal(2, result.Count()); - Assert.Equal(objectTrigger, result.First().Trigger); - Assert.Equal(concreteTrigger, result.Last().Trigger); - } + Assert.Equal(2, result.Count()); + Assert.Equal(objectTrigger, result.First().Trigger); + Assert.Equal(concreteTrigger, result.Last().Trigger); + } - [Fact] - public void DiscoverChangeHandlerInvocations_SortTriggersByBaseTypeThenInterfacesThenDerivedType() - { - var interfaceTrigger = new TriggerStub(); - var objectTrigger = new TriggerStub(); - var concreteTrigger = new TriggerStub(); + [Fact] + public void DiscoverChangeHandlerInvocations_SortTriggersByBaseTypeThenInterfacesThenDerivedType() + { + var interfaceTrigger = new TriggerStub(); + var objectTrigger = new TriggerStub(); + var concreteTrigger = new TriggerStub(); - var serviceProvider = new ServiceCollection() - .AddSingleton>(interfaceTrigger) - .AddSingleton>(concreteTrigger) - .AddSingleton>(objectTrigger) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddSingleton>(interfaceTrigger) + .AddSingleton>(concreteTrigger) + .AddSingleton>(objectTrigger) + .BuildServiceProvider(); - var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); + var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); - var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); + var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); - Assert.Equal(3, result.Count()); - Assert.Equal(objectTrigger, result.First().Trigger); - Assert.Equal(interfaceTrigger, result.Skip(1).First().Trigger); - Assert.Equal(concreteTrigger, result.Last().Trigger); - } + Assert.Equal(3, result.Count()); + Assert.Equal(objectTrigger, result.First().Trigger); + Assert.Equal(interfaceTrigger, result.Skip(1).First().Trigger); + Assert.Equal(concreteTrigger, result.Last().Trigger); + } - [Fact] - public void DiscoverChangeHandlerInvocations_SortByPriorities() - { - var earlyTrigger = new TriggerStub { Priority = CommonTriggerPriority.Early }; - var lateTrigger = new TriggerStub { Priority = CommonTriggerPriority.Late }; + [Fact] + public void DiscoverChangeHandlerInvocations_SortByPriorities() + { + var earlyTrigger = new TriggerStub { Priority = CommonTriggerPriority.Early }; + var lateTrigger = new TriggerStub { Priority = CommonTriggerPriority.Late }; - var serviceProvider = new ServiceCollection() - .AddSingleton>(lateTrigger) - .AddSingleton>(earlyTrigger) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddSingleton>(lateTrigger) + .AddSingleton>(earlyTrigger) + .BuildServiceProvider(); - var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); + var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(serviceProvider), new TriggerTypeRegistryService(), new TriggerFactory(serviceProvider)); - var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); + var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); - Assert.Equal(2, result.Count()); - Assert.Equal(earlyTrigger, result.First().Trigger); - Assert.Equal(lateTrigger, result.Last().Trigger); - } + Assert.Equal(2, result.Count()); + Assert.Equal(earlyTrigger, result.First().Trigger); + Assert.Equal(lateTrigger, result.Last().Trigger); + } - [Fact] - public void SetServiceProvider_OverridesDefaultServiceProvider() - { - var defaultServiceProviderTrigger = new TriggerStub(); - var externalServiceProviderTrigger = new TriggerStub(); + [Fact] + public void SetServiceProvider_OverridesDefaultServiceProvider() + { + var defaultServiceProviderTrigger = new TriggerStub(); + var externalServiceProviderTrigger = new TriggerStub(); - var defaultServiceProvider = new ServiceCollection() - .BuildServiceProvider(); + var defaultServiceProvider = new ServiceCollection() + .BuildServiceProvider(); - var externalServiceProvider = new ServiceCollection() - .AddSingleton>(externalServiceProviderTrigger) - .BuildServiceProvider(); + var externalServiceProvider = new ServiceCollection() + .AddSingleton>(externalServiceProviderTrigger) + .BuildServiceProvider(); - var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(defaultServiceProvider), new TriggerTypeRegistryService(), new TriggerFactory(defaultServiceProvider)); - subject.ServiceProvider = externalServiceProvider; + var subject = new TriggerDiscoveryService(new TriggerServiceProviderAccessor(defaultServiceProvider), new TriggerTypeRegistryService(), new TriggerFactory(defaultServiceProvider)); + subject.ServiceProvider = externalServiceProvider; - var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); + var result = subject.DiscoverTriggers(typeof(IBeforeSaveTrigger<>), typeof(string), type => new BeforeSaveTriggerDescriptor(type)); - Assert.Single(result); - } + Assert.Single(result); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs index 4c7bba2..d3698ab 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerFactoryTests.cs @@ -5,123 +5,122 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerFactoryTests { - public class TriggerFactoryTests + class SampleTrigger : IBeforeSaveTrigger { - class SampleTrigger : IBeforeSaveTrigger - { - public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); - } + public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); + } - class SampleTrigger2(TriggerFactory triggerFactory) : IBeforeSaveTrigger - { - public TriggerFactory TriggerFactory { get; } = triggerFactory; + class SampleTrigger2(TriggerFactory triggerFactory) : IBeforeSaveTrigger + { + public TriggerFactory TriggerFactory { get; } = triggerFactory; - public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); - } + public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); + } - class SampleTrigger3(TDbContext dbContext) : IBeforeSaveTrigger - where TDbContext : DbContext - { - public TDbContext DbContext { get; } = dbContext; + class SampleTrigger3(TDbContext dbContext) : IBeforeSaveTrigger + where TDbContext : DbContext + { + public TDbContext DbContext { get; } = dbContext; - public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); - } + public void BeforeSave(ITriggerContext context) => throw new NotImplementedException(); + } - public class SampleDbContext3 : DbContext + public class SampleDbContext3 : DbContext + { + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder - .UseInMemoryDatabase(nameof(SampleDbContext3)) - .UseTriggers(triggerOptions => - triggerOptions - .AddTrigger>() - .AddTrigger>() - ); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - } + optionsBuilder + .UseInMemoryDatabase(nameof(SampleDbContext3)) + .UseTriggers(triggerOptions => + triggerOptions + .AddTrigger>() + .AddTrigger>() + ); + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); } + } - [Fact] - public void Resolve_FromExternalServiceProvider_FindsType() - { - var serviceProvider = new ServiceCollection().BuildServiceProvider(); + [Fact] + public void Resolve_FromExternalServiceProvider_FindsType() + { + var serviceProvider = new ServiceCollection().BuildServiceProvider(); - var applicationServiceProvider = new ServiceCollection() - .AddTransient, SampleTrigger>() - .BuildServiceProvider(); + var applicationServiceProvider = new ServiceCollection() + .AddTransient, SampleTrigger>() + .BuildServiceProvider(); - var subject = new TriggerFactory(serviceProvider); + var subject = new TriggerFactory(serviceProvider); - var triggers = subject.Resolve(applicationServiceProvider, typeof(IBeforeSaveTrigger)); + var triggers = subject.Resolve(applicationServiceProvider, typeof(IBeforeSaveTrigger)); - Assert.Single(triggers); - } + Assert.Single(triggers); + } - [Fact] - public void Resolve_FromInternalServices_FindsType() - { - var serviceProvider = new ServiceCollection() - .AddTransient(typeof(ITriggerInstanceFactory>), _ => new TriggerInstanceFactory(null)) - .BuildServiceProvider(); + [Fact] + public void Resolve_FromInternalServices_FindsType() + { + var serviceProvider = new ServiceCollection() + .AddTransient(typeof(ITriggerInstanceFactory>), _ => new TriggerInstanceFactory(null)) + .BuildServiceProvider(); - var applicationServiceProvider = new ServiceCollection().BuildServiceProvider(); + var applicationServiceProvider = new ServiceCollection().BuildServiceProvider(); - var subject = new TriggerFactory(serviceProvider); + var subject = new TriggerFactory(serviceProvider); - var triggers = subject.Resolve(applicationServiceProvider, typeof(IBeforeSaveTrigger)); + var triggers = subject.Resolve(applicationServiceProvider, typeof(IBeforeSaveTrigger)); - Assert.Single(triggers); - } + Assert.Single(triggers); + } - [Fact] - public void Resolve_FromInternalServices_GetsConstructedUsingExternalServiceProvider() - { - var serviceProvider = new ServiceCollection() - .AddLogging() - .AddTransient(typeof(ITriggerInstanceFactory>), _ => new TriggerInstanceFactory(null)) - .BuildServiceProvider(); + [Fact] + public void Resolve_FromInternalServices_GetsConstructedUsingExternalServiceProvider() + { + var serviceProvider = new ServiceCollection() + .AddLogging() + .AddTransient(typeof(ITriggerInstanceFactory>), _ => new TriggerInstanceFactory(null)) + .BuildServiceProvider(); - var subject = new TriggerFactory(serviceProvider); + var subject = new TriggerFactory(serviceProvider); - var applicationServiceProvider = new ServiceCollection() - .AddSingleton(subject) - .BuildServiceProvider(); + var applicationServiceProvider = new ServiceCollection() + .AddSingleton(subject) + .BuildServiceProvider(); - var trigger = subject.Resolve(applicationServiceProvider, typeof(IBeforeSaveTrigger)).FirstOrDefault() as SampleTrigger2; + var trigger = subject.Resolve(applicationServiceProvider, typeof(IBeforeSaveTrigger)).FirstOrDefault() as SampleTrigger2; - Assert.NotNull(trigger); - Assert.Equal(subject, trigger.TriggerFactory); - } + Assert.NotNull(trigger); + Assert.Equal(subject, trigger.TriggerFactory); + } - [Fact] - public void Resolve_FromHybridServices_GetsPasedTheConcreteDbContext() - { - using var dbContext = new SampleDbContext3(); - var factory = dbContext.GetService(); - var serviceProvider = new HybridServiceProvider(dbContext.GetInfrastructure(), dbContext); + [Fact] + public void Resolve_FromHybridServices_GetsPasedTheConcreteDbContext() + { + using var dbContext = new SampleDbContext3(); + var factory = dbContext.GetService(); + var serviceProvider = new HybridServiceProvider(dbContext.GetInfrastructure(), dbContext); - var trigger = factory.Resolve(serviceProvider, typeof(IBeforeSaveTrigger)).FirstOrDefault() as SampleTrigger3; + var trigger = factory.Resolve(serviceProvider, typeof(IBeforeSaveTrigger)).FirstOrDefault() as SampleTrigger3; - Assert.NotNull(trigger); - Assert.Equal(dbContext, trigger.DbContext); - } + Assert.NotNull(trigger); + Assert.Equal(dbContext, trigger.DbContext); + } - [Fact] - public void Resolve_FromHybridServices_GetsPasedTheAbstractDbContext() - { - using var dbContext = new SampleDbContext3(); - var factory = dbContext.GetService(); - var serviceProvider = new HybridServiceProvider(dbContext.GetInfrastructure(), dbContext); + [Fact] + public void Resolve_FromHybridServices_GetsPasedTheAbstractDbContext() + { + using var dbContext = new SampleDbContext3(); + var factory = dbContext.GetService(); + var serviceProvider = new HybridServiceProvider(dbContext.GetInfrastructure(), dbContext); - var trigger = factory.Resolve(serviceProvider, typeof(IBeforeSaveTrigger)).LastOrDefault() as SampleTrigger3; + var trigger = factory.Resolve(serviceProvider, typeof(IBeforeSaveTrigger)).LastOrDefault() as SampleTrigger3; - Assert.NotNull(trigger); - Assert.Equal(dbContext, trigger.DbContext); - } + Assert.NotNull(trigger); + Assert.Equal(dbContext, trigger.DbContext); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerInstanceFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerInstanceFactoryTests.cs index 2b0b731..639ab2a 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerInstanceFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerInstanceFactoryTests.cs @@ -4,53 +4,52 @@ using ScenarioTests; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public partial class TriggerInstanceFactoryTests { - public partial class TriggerInstanceFactoryTests + class SampleDbContext(DbContextOptions options) : DbContext(options) { - class SampleDbContext(DbContextOptions options) : DbContext(options) - { - } + } - class SampleTrigger1 { } + class SampleTrigger1 { } #pragma warning disable CS9113 // Parameter is unread. - class SampleTrigger2(TriggerInstanceFactoryTests.SampleDbContext sampleDbContext) + class SampleTrigger2(TriggerInstanceFactoryTests.SampleDbContext sampleDbContext) #pragma warning restore CS9113 // Parameter is unread. - { - } - - [Scenario] - public void TriggerInstanceFactoriesBehaviorTests(ScenarioContext scenario) - { - var serviceProvider = new ServiceCollection() - .AddDbContext() - .BuildServiceProvider(); - - var dbContext = serviceProvider.GetRequiredService(); - - ITriggerInstanceFactory subject = new TriggerInstanceFactory(null); - var instance = subject.Create(serviceProvider); - - scenario.Fact("Creates an instance on first request", () => { - Assert.NotNull(instance); - }); - - scenario.Fact("Caches that instance on subsequent requests", () => { - var secondInstance = subject.Create(serviceProvider); - Assert.Equal(instance, secondInstance); - }); - - scenario.Fact("When provided with an initial instance, it will always return that", () => { - subject = new TriggerInstanceFactory(instance); - var secondInstance = subject.Create(serviceProvider); - Assert.Equal(instance, secondInstance); - }); - - scenario.Fact("Gets provided the DbContext when its requested", () => { - subject = new TriggerInstanceFactory(null); - instance = subject.Create(serviceProvider); - Assert.NotNull(instance); - }); - } + { + } + + [Scenario] + public void TriggerInstanceFactoriesBehaviorTests(ScenarioContext scenario) + { + var serviceProvider = new ServiceCollection() + .AddDbContext() + .BuildServiceProvider(); + + var dbContext = serviceProvider.GetRequiredService(); + + ITriggerInstanceFactory subject = new TriggerInstanceFactory(null); + var instance = subject.Create(serviceProvider); + + scenario.Fact("Creates an instance on first request", () => { + Assert.NotNull(instance); + }); + + scenario.Fact("Caches that instance on subsequent requests", () => { + var secondInstance = subject.Create(serviceProvider); + Assert.Equal(instance, secondInstance); + }); + + scenario.Fact("When provided with an initial instance, it will always return that", () => { + subject = new TriggerInstanceFactory(instance); + var secondInstance = subject.Create(serviceProvider); + Assert.Equal(instance, secondInstance); + }); + + scenario.Fact("Gets provided the DbContext when its requested", () => { + subject = new TriggerInstanceFactory(null); + instance = subject.Create(serviceProvider); + Assert.NotNull(instance); + }); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs index f0f2d40..82ff323 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerSessionSaveChangesInterceptorTests.cs @@ -6,302 +6,301 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerSessionSaveChangesInterceptorTests { - public class TriggerSessionSaveChangesInterceptorTests + public class TestModel { - public class TestModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } + public Guid Id { get; set; } + public string Name { get; set; } + } - class TestDbContext(bool stubService = true) : DbContext - { - readonly bool _stubService = stubService; - public SqliteConnection UseSqlLiteConnection; + class TestDbContext(bool stubService = true) : DbContext + { + readonly bool _stubService = stubService; + public SqliteConnection UseSqlLiteConnection; + + public TriggerStub TriggerStub { get; } = new TriggerStub(); - public TriggerStub TriggerStub { get; } = new TriggerStub(); + public DbSet TestModels { get; set; } - public DbSet TestModels { get; set; } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); + + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + if (UseSqlLiteConnection != null) { - base.OnConfiguring(optionsBuilder); - - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - - if (UseSqlLiteConnection != null) - { - optionsBuilder.UseSqlite(UseSqlLiteConnection); - } - else - { - optionsBuilder.UseInMemoryDatabase("test"); - } - optionsBuilder.UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(TriggerStub); - }); - - if (_stubService) - { - optionsBuilder.ReplaceService(); - } + optionsBuilder.UseSqlite(UseSqlLiteConnection); } - - protected override void OnModelCreating(ModelBuilder modelBuilder) + else { - modelBuilder.Entity().HasKey(x => x.Id); + optionsBuilder.UseInMemoryDatabase("test"); + } + optionsBuilder.UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(TriggerStub); + }); - base.OnModelCreating(modelBuilder); + if (_stubService) + { + optionsBuilder.ReplaceService(); } } - TestDbContext CreateSubject(bool stubService = true) - => new(stubService); - - [Fact] - public void SaveChanges_RaisesBeforeSaveChangesStartingTriggers() + protected override void OnModelCreating(ModelBuilder modelBuilder) { - var subject = new TestDbContext(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + modelBuilder.Entity().HasKey(x => x.Id); - subject.SaveChanges(); - - Assert.Equal(1, triggerServiceStub.LastSession.RaiseBeforeSaveStartingTriggersCalls); + base.OnModelCreating(modelBuilder); } + } + TestDbContext CreateSubject(bool stubService = true) + => new(stubService); - [Fact] - public void SaveChanges_RaisesBeforeSaveChangesCompletedTriggers() - { - var subject = new TestDbContext(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - - subject.SaveChanges(); - - Assert.Equal(1, triggerServiceStub.LastSession.RaiseBeforeSaveCompletingTriggersCalls); - } + [Fact] + public void SaveChanges_RaisesBeforeSaveChangesStartingTriggers() + { + var subject = new TestDbContext(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - [Fact] - public void SaveChanges_RaisesAfterSaveChangesStartingTriggers() - { - var subject = new TestDbContext(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + subject.SaveChanges(); - subject.SaveChanges(); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseBeforeSaveStartingTriggersCalls); + } - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveStartingTriggersCalls); - } + [Fact] + public void SaveChanges_RaisesBeforeSaveChangesCompletedTriggers() + { + var subject = new TestDbContext(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - [Fact] - public void SaveChanges_RaisesAfterSaveChangesCompletedTriggers() - { - var subject = new TestDbContext(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + subject.SaveChanges(); - subject.SaveChanges(); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseBeforeSaveCompletingTriggersCalls); + } - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveCompletedTriggersCalls); - } + [Fact] + public void SaveChanges_RaisesAfterSaveChangesStartingTriggers() + { + var subject = new TestDbContext(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - [Fact] - public void SaveChanges_OnDbUpdateException_RaisesAfterSaveFailedStartingTriggers() - { - using var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - - var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; - prepDbContext.Database.EnsureCreated(); - var duplicatedId = Guid.NewGuid(); - prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); - prepDbContext.SaveChanges(); - - var subject = new TestDbContext() { UseSqlLiteConnection = connection }; - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - - // Inserting a model with the same Id should fail in the database - subject.TestModels.Add(new TestModel { - Id = duplicatedId, - Name = "test1" - }); + subject.SaveChanges(); - Assert.Throws(() => subject.SaveChanges()); - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedStartingTriggersCalls); - } + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveStartingTriggersCalls); + } - [Fact] - public void SaveChanges_OnDbUpdateException_RaisesAfterSaveFailedCompletedTriggers() - { - using var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - - var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; - prepDbContext.Database.EnsureCreated(); - var duplicatedId = Guid.NewGuid(); - prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); - prepDbContext.SaveChanges(); - - var subject = new TestDbContext() { UseSqlLiteConnection = connection }; - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - - // Inserting a model with the same Id should fail in the database - subject.TestModels.Add(new TestModel { - Id = duplicatedId, - Name = "test1" - }); - Assert.Throws(() => subject.SaveChanges()); - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedCompletedTriggersCalls); - } + [Fact] + public void SaveChanges_RaisesAfterSaveChangesCompletedTriggers() + { + var subject = new TestDbContext(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - [Fact] - public async Task SaveChangesAsync_RaisesBeforeSaveChangesStartingTriggers() - { - var subject = new TestDbContext(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + subject.SaveChanges(); - await subject.SaveChangesAsync(); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveCompletedTriggersCalls); + } - Assert.Equal(1, triggerServiceStub.LastSession.RaiseBeforeSaveStartingTriggersCalls); - } + [Fact] + public void SaveChanges_OnDbUpdateException_RaisesAfterSaveFailedStartingTriggers() + { + using var connection = new SqliteConnection("DataSource=:memory:"); + connection.Open(); + + var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; + prepDbContext.Database.EnsureCreated(); + var duplicatedId = Guid.NewGuid(); + prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); + prepDbContext.SaveChanges(); + + var subject = new TestDbContext() { UseSqlLiteConnection = connection }; + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + + // Inserting a model with the same Id should fail in the database + subject.TestModels.Add(new TestModel { + Id = duplicatedId, + Name = "test1" + }); + + Assert.Throws(() => subject.SaveChanges()); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedStartingTriggersCalls); + } + [Fact] + public void SaveChanges_OnDbUpdateException_RaisesAfterSaveFailedCompletedTriggers() + { + using var connection = new SqliteConnection("DataSource=:memory:"); + connection.Open(); + + var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; + prepDbContext.Database.EnsureCreated(); + var duplicatedId = Guid.NewGuid(); + prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); + prepDbContext.SaveChanges(); + + var subject = new TestDbContext() { UseSqlLiteConnection = connection }; + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + + // Inserting a model with the same Id should fail in the database + subject.TestModels.Add(new TestModel { + Id = duplicatedId, + Name = "test1" + }); + + Assert.Throws(() => subject.SaveChanges()); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedCompletedTriggersCalls); + } - [Fact] - public async Task SaveChangesAsync_RaisesBeforeSaveChangesCompletedTriggers() - { - var subject = new TestDbContext(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + [Fact] + public async Task SaveChangesAsync_RaisesBeforeSaveChangesStartingTriggers() + { + var subject = new TestDbContext(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - await subject.SaveChangesAsync(); + await subject.SaveChangesAsync(); - Assert.Equal(1, triggerServiceStub.LastSession.RaiseBeforeSaveCompletingTriggersCalls); - } + Assert.Equal(1, triggerServiceStub.LastSession.RaiseBeforeSaveStartingTriggersCalls); + } - [Fact] - public async Task SaveChangesAsync_RaisesAfterSaveChangesStartingTriggers() - { - var subject = new TestDbContext(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - await subject.SaveChangesAsync(); + [Fact] + public async Task SaveChangesAsync_RaisesBeforeSaveChangesCompletedTriggers() + { + var subject = new TestDbContext(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveStartingTriggersCalls); - } + await subject.SaveChangesAsync(); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseBeforeSaveCompletingTriggersCalls); + } - [Fact] - public async Task SaveChangesAsync_RaisesAfterSaveChangesCompletedTriggers() - { - var subject = new TestDbContext(); - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + [Fact] + public async Task SaveChangesAsync_RaisesAfterSaveChangesStartingTriggers() + { + var subject = new TestDbContext(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - await subject.SaveChangesAsync(); + await subject.SaveChangesAsync(); - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveCompletedTriggersCalls); - } + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveStartingTriggersCalls); + } - [Fact] - public async Task SaveChangesAsync_OnDbUpdateException_RaisesAfterSaveFailedStartingTriggers() - { - using var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - - var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; - prepDbContext.Database.EnsureCreated(); - var duplicatedId = Guid.NewGuid(); - prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); - prepDbContext.SaveChanges(); - - var subject = new TestDbContext() { UseSqlLiteConnection = connection }; - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - - // Inserting a model with the same Id should fail in the database - subject.TestModels.Add(new TestModel { - Id = duplicatedId, - Name = "test1" - }); - await Assert.ThrowsAsync(() => subject.SaveChangesAsync()); - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedStartingTriggersCalls); - } + [Fact] + public async Task SaveChangesAsync_RaisesAfterSaveChangesCompletedTriggers() + { + var subject = new TestDbContext(); + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - [Fact] - public async Task SaveChangesAsync_OnDbUpdateException_RaisesAfterSaveFailedCompletedTriggers() - { - using var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - - var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; - prepDbContext.Database.EnsureCreated(); - var duplicatedId = Guid.NewGuid(); - prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); - prepDbContext.SaveChanges(); - - var subject = new TestDbContext() { UseSqlLiteConnection = connection }; - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - - // Inserting a model with the same Id should fail in the database - subject.TestModels.Add(new TestModel { - Id = duplicatedId, - Name = "test1" - }); + await subject.SaveChangesAsync(); - await Assert.ThrowsAsync(() => subject.SaveChangesAsync()); - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedCompletedTriggersCalls); - } + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveCompletedTriggersCalls); + } - [Fact] - public void SaveChanges_OnDbUpdateException_RaisesAfterSaveFailedTriggers() - { - using var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - - var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; - prepDbContext.Database.EnsureCreated(); - var duplicatedId = Guid.NewGuid(); - prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); - prepDbContext.SaveChanges(); - - var subject = new TestDbContext() { UseSqlLiteConnection = connection }; - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - - // Inserting a model with the same Id should fail in the database - subject.TestModels.Add(new TestModel { - Id = duplicatedId, - Name = "test1" - }); + [Fact] + public async Task SaveChangesAsync_OnDbUpdateException_RaisesAfterSaveFailedStartingTriggers() + { + using var connection = new SqliteConnection("DataSource=:memory:"); + connection.Open(); + + var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; + prepDbContext.Database.EnsureCreated(); + var duplicatedId = Guid.NewGuid(); + prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); + prepDbContext.SaveChanges(); + + var subject = new TestDbContext() { UseSqlLiteConnection = connection }; + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + + // Inserting a model with the same Id should fail in the database + subject.TestModels.Add(new TestModel { + Id = duplicatedId, + Name = "test1" + }); + + await Assert.ThrowsAsync(() => subject.SaveChangesAsync()); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedStartingTriggersCalls); + } - Assert.Throws(() => subject.SaveChanges()); - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedTriggersCalls); - } + [Fact] + public async Task SaveChangesAsync_OnDbUpdateException_RaisesAfterSaveFailedCompletedTriggers() + { + using var connection = new SqliteConnection("DataSource=:memory:"); + connection.Open(); + + var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; + prepDbContext.Database.EnsureCreated(); + var duplicatedId = Guid.NewGuid(); + prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); + prepDbContext.SaveChanges(); + + var subject = new TestDbContext() { UseSqlLiteConnection = connection }; + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + + // Inserting a model with the same Id should fail in the database + subject.TestModels.Add(new TestModel { + Id = duplicatedId, + Name = "test1" + }); + + await Assert.ThrowsAsync(() => subject.SaveChangesAsync()); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedCompletedTriggersCalls); + } - [Fact] - public async Task SaveChangesAsync_OnDbUpdateException_RaisesAfterSaveFailedTriggers() - { - using var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - - var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; - prepDbContext.Database.EnsureCreated(); - var duplicatedId = Guid.NewGuid(); - prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); - prepDbContext.SaveChanges(); - - var subject = new TestDbContext() { UseSqlLiteConnection = connection }; - var triggerServiceStub = (TriggerServiceStub)subject.GetService(); - - // Inserting a model with the same Id should fail in the database - subject.TestModels.Add(new TestModel { - Id = duplicatedId, - Name = "test1" - }); + [Fact] + public void SaveChanges_OnDbUpdateException_RaisesAfterSaveFailedTriggers() + { + using var connection = new SqliteConnection("DataSource=:memory:"); + connection.Open(); + + var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; + prepDbContext.Database.EnsureCreated(); + var duplicatedId = Guid.NewGuid(); + prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); + prepDbContext.SaveChanges(); + + var subject = new TestDbContext() { UseSqlLiteConnection = connection }; + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + + // Inserting a model with the same Id should fail in the database + subject.TestModels.Add(new TestModel { + Id = duplicatedId, + Name = "test1" + }); + + Assert.Throws(() => subject.SaveChanges()); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedTriggersCalls); + } - await Assert.ThrowsAsync(async () => await subject.SaveChangesAsync()); - Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedTriggersCalls); - } + [Fact] + public async Task SaveChangesAsync_OnDbUpdateException_RaisesAfterSaveFailedTriggers() + { + using var connection = new SqliteConnection("DataSource=:memory:"); + connection.Open(); + + var prepDbContext = new TestDbContext(false) { UseSqlLiteConnection = connection }; + prepDbContext.Database.EnsureCreated(); + var duplicatedId = Guid.NewGuid(); + prepDbContext.TestModels.Add(new TestModel { Id = duplicatedId }); + prepDbContext.SaveChanges(); + + var subject = new TestDbContext() { UseSqlLiteConnection = connection }; + var triggerServiceStub = (TriggerServiceStub)subject.GetService(); + + // Inserting a model with the same Id should fail in the database + subject.TestModels.Add(new TestModel { + Id = duplicatedId, + Name = "test1" + }); + + await Assert.ThrowsAsync(async () => await subject.SaveChangesAsync()); + Assert.Equal(1, triggerServiceStub.LastSession.RaiseAfterSaveFailedTriggersCalls); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeDescriptorHelpersTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeDescriptorHelpersTests.cs index 49df3ea..6f1213b 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeDescriptorHelpersTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeDescriptorHelpersTests.cs @@ -2,32 +2,31 @@ using EntityFrameworkCore.Triggered.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerTypeDescriptorHelpersTests { - public class TriggerTypeDescriptorHelpersTests + [Fact] + public void CreateWeakDelegate_WrapsTargetMethod() { - [Fact] - public void CreateWeakDelegate_WrapsTargetMethod() - { - var triggerStub = new TriggerStub(); - var triggerContextStub = new TriggerContextStub(); - var weakDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(typeof(IBeforeSaveTrigger), typeof(object), typeof(IBeforeSaveTrigger).GetMethod("BeforeSave")); + var triggerStub = new TriggerStub(); + var triggerContextStub = new TriggerContextStub(); + var weakDelegate = TriggerTypeDescriptorHelpers.GetWeakDelegate(typeof(IBeforeSaveTrigger), typeof(object), typeof(IBeforeSaveTrigger).GetMethod("BeforeSave")); - weakDelegate(triggerStub, triggerContextStub); + weakDelegate(triggerStub, triggerContextStub); - Assert.NotEmpty(triggerStub.BeforeSaveInvocations); - } + Assert.NotEmpty(triggerStub.BeforeSaveInvocations); + } - [Fact] - public async Task CreateAsyncWeakDelegate_WrapsTargetMethod() - { - var triggerStub = new TriggerStub(); - var triggerContextStub = new TriggerContextStub(); - var weakDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(typeof(IBeforeSaveAsyncTrigger), typeof(object), typeof(IBeforeSaveAsyncTrigger).GetMethod("BeforeSaveAsync")); + [Fact] + public async Task CreateAsyncWeakDelegate_WrapsTargetMethod() + { + var triggerStub = new TriggerStub(); + var triggerContextStub = new TriggerContextStub(); + var weakDelegate = TriggerTypeDescriptorHelpers.GetAsyncWeakDelegate(typeof(IBeforeSaveAsyncTrigger), typeof(object), typeof(IBeforeSaveAsyncTrigger).GetMethod("BeforeSaveAsync")); - await weakDelegate(triggerStub, triggerContextStub, default); + await weakDelegate(triggerStub, triggerContextStub, default); - Assert.NotEmpty(triggerStub.BeforeSaveAsyncInvocations); - } + Assert.NotEmpty(triggerStub.BeforeSaveAsyncInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryServiceTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryServiceTests.cs index 13c13d8..36851ae 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryServiceTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryServiceTests.cs @@ -2,45 +2,44 @@ using EntityFrameworkCore.Triggered.Internal.Descriptors; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerTypeRegistryServiceTests { - public class TriggerTypeRegistryServiceTests + [Fact] + public void ResolveRegistry_SameTypePattern_ReturnsSameInstance() { - [Fact] - public void ResolveRegistry_SameTypePattern_ReturnsSameInstance() - { - var subject = new TriggerTypeRegistryService(); - var triggerType = typeof(IBeforeSaveTrigger<>); - var entityType = typeof(object); - - var registry1 = subject.ResolveRegistry(triggerType, entityType, _ => null); - var registry2 = subject.ResolveRegistry(triggerType, entityType, _ => null); - - Assert.Equal(registry1, registry2); - } - - [Fact] - public void ResolveRegistry_DifferentEntityType_ReturnsSameInstance() - { - var subject = new TriggerTypeRegistryService(); - var triggerType = typeof(IBeforeSaveTrigger<>); - - var registry1 = subject.ResolveRegistry(triggerType, typeof(object), _ => null); - var registry2 = subject.ResolveRegistry(triggerType, typeof(string), _ => null); - - Assert.NotEqual(registry1, registry2); - } - - [Fact] - public void ResolveRegistry_DifferentTriggerType_ReturnsDifferentInstance() - { - var subject = new TriggerTypeRegistryService(); - var entityType = typeof(object); - - var registry1 = subject.ResolveRegistry(typeof(IBeforeSaveTrigger<>), entityType, _ => null); - var registry2 = subject.ResolveRegistry(typeof(IAfterSaveTrigger<>), entityType, _ => null); - - Assert.NotEqual(registry1, registry2); - } + var subject = new TriggerTypeRegistryService(); + var triggerType = typeof(IBeforeSaveTrigger<>); + var entityType = typeof(object); + + var registry1 = subject.ResolveRegistry(triggerType, entityType, _ => null); + var registry2 = subject.ResolveRegistry(triggerType, entityType, _ => null); + + Assert.Equal(registry1, registry2); + } + + [Fact] + public void ResolveRegistry_DifferentEntityType_ReturnsSameInstance() + { + var subject = new TriggerTypeRegistryService(); + var triggerType = typeof(IBeforeSaveTrigger<>); + + var registry1 = subject.ResolveRegistry(triggerType, typeof(object), _ => null); + var registry2 = subject.ResolveRegistry(triggerType, typeof(string), _ => null); + + Assert.NotEqual(registry1, registry2); + } + + [Fact] + public void ResolveRegistry_DifferentTriggerType_ReturnsDifferentInstance() + { + var subject = new TriggerTypeRegistryService(); + var entityType = typeof(object); + + var registry1 = subject.ResolveRegistry(typeof(IBeforeSaveTrigger<>), entityType, _ => null); + var registry2 = subject.ResolveRegistry(typeof(IAfterSaveTrigger<>), entityType, _ => null); + + Assert.NotEqual(registry1, registry2); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryTests.cs index eaf06a9..edd63ab 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TriggerTypeRegistryTests.cs @@ -2,73 +2,72 @@ using EntityFrameworkCore.Triggered.Internal.Descriptors; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerTypeRegistryTests { - public class TriggerTypeRegistryTests - { - public class BaseType { } - public class DerivedType : BaseType { } - public interface IInterfaceType { } - public class BaseTypeWithInterface : IInterfaceType { } - public class DerivedTypeWithInterface : BaseTypeWithInterface, IInterfaceType { } + public class BaseType { } + public class DerivedType : BaseType { } + public interface IInterfaceType { } + public class BaseTypeWithInterface : IInterfaceType { } + public class DerivedTypeWithInterface : BaseTypeWithInterface, IInterfaceType { } - TriggerTypeRegistry CreateSubject() - => new(typeof(TType), type => new BeforeSaveTriggerDescriptor(type)); + TriggerTypeRegistry CreateSubject() + => new(typeof(TType), type => new BeforeSaveTriggerDescriptor(type)); - [Fact] - public void GetTriggerTypeDescriptors_ForObject_Returns1Descriptor() - { - var subject = CreateSubject(); - var result = subject.GetTriggerTypeDescriptors(); + [Fact] + public void GetTriggerTypeDescriptors_ForObject_Returns1Descriptor() + { + var subject = CreateSubject(); + var result = subject.GetTriggerTypeDescriptors(); - Assert.Single(result); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); - } + Assert.Single(result); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); + } - [Fact] - public void GetTriggerTypeDescriptors_ForBaseType_Returns2DescriptorsInOrder() - { - var subject = CreateSubject(); - var result = subject.GetTriggerTypeDescriptors(); + [Fact] + public void GetTriggerTypeDescriptors_ForBaseType_Returns2DescriptorsInOrder() + { + var subject = CreateSubject(); + var result = subject.GetTriggerTypeDescriptors(); - Assert.Equal(2, result.Length); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(1).First().TriggerType); - } + Assert.Equal(2, result.Length); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(1).First().TriggerType); + } - [Fact] - public void GetTriggerTypeDescriptors_ForInterfaceType_Returns1Descriptor() - { - var subject = CreateSubject(); - var result = subject.GetTriggerTypeDescriptors(); + [Fact] + public void GetTriggerTypeDescriptors_ForInterfaceType_Returns1Descriptor() + { + var subject = CreateSubject(); + var result = subject.GetTriggerTypeDescriptors(); - Assert.Single(result); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); - } + Assert.Single(result); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); + } - [Fact] - public void GetTriggerTypeDescriptors_ForBaseTypeWithInterface_Returns3DescriptorsInOrder() - { - var subject = CreateSubject(); - var result = subject.GetTriggerTypeDescriptors(); + [Fact] + public void GetTriggerTypeDescriptors_ForBaseTypeWithInterface_Returns3DescriptorsInOrder() + { + var subject = CreateSubject(); + var result = subject.GetTriggerTypeDescriptors(); - Assert.Equal(3, result.Length); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(1).First().TriggerType); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(2).First().TriggerType); - } + Assert.Equal(3, result.Length); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(1).First().TriggerType); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(2).First().TriggerType); + } - [Fact] - public void GetTriggerTypeDescriptors_ForDerivedTypeWithInterface_Returns4DescriptorsInOrder() - { - var subject = CreateSubject(); - var result = subject.GetTriggerTypeDescriptors(); + [Fact] + public void GetTriggerTypeDescriptors_ForDerivedTypeWithInterface_Returns4DescriptorsInOrder() + { + var subject = CreateSubject(); + var result = subject.GetTriggerTypeDescriptors(); - Assert.Equal(4, result.Length); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(1).First().TriggerType); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(2).First().TriggerType); - Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(3).First().TriggerType); - } + Assert.Equal(4, result.Length); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(0).First().TriggerType); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(1).First().TriggerType); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(2).First().TriggerType); + Assert.Equal(typeof(IBeforeSaveTrigger), result.Skip(3).First().TriggerType); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Internal/TypeHelpersTests.cs b/test/EntityFrameworkCore.Triggered.Tests/Internal/TypeHelpersTests.cs index 767ab1a..868a906 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Internal/TypeHelpersTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Internal/TypeHelpersTests.cs @@ -1,30 +1,29 @@ using EntityFrameworkCore.Triggered.Infrastructure.Internal; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TypeHelpersTests { - public class TypeHelpersTests + [Theory] + [InlineData(typeof(List<>), typeof(ICollection<>), true)] + [InlineData(typeof(List), typeof(ICollection<>), true)] + [InlineData(typeof(object), typeof(IBeforeSaveTrigger<>), false)] + public void FindGenericInterface_DetectsImplementation(Type type, Type interfaceType, bool expectedResult) { - [Theory] - [InlineData(typeof(List<>), typeof(ICollection<>), true)] - [InlineData(typeof(List), typeof(ICollection<>), true)] - [InlineData(typeof(object), typeof(IBeforeSaveTrigger<>), false)] - public void FindGenericInterface_DetectsImplementation(Type type, Type interfaceType, bool expectedResult) - { - var result = TypeHelpers.FindGenericInterfaces(type, interfaceType).Any(); + var result = TypeHelpers.FindGenericInterfaces(type, interfaceType).Any(); - Assert.Equal(expectedResult, result); - } + Assert.Equal(expectedResult, result); + } - [Fact] - public void EnumerateTypeHierarchy_Object_FindsOne() - { - var type = typeof(object); + [Fact] + public void EnumerateTypeHierarchy_Object_FindsOne() + { + var type = typeof(object); - var result = TypeHelpers.EnumerateTypeHierarchy(type); + var result = TypeHelpers.EnumerateTypeHierarchy(type); - Assert.Single(result); - Assert.Equal(type, result.Single()); - } + Assert.Single(result); + Assert.Equal(type, result.Single()); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs index af136c1..0a07248 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/BeforeSaveDelegatingTrigger.cs @@ -1,11 +1,10 @@ -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs; + +public class BeforeSaveDelegatingTrigger(Func, CancellationToken, Task> handler) : IBeforeSaveTrigger, IBeforeSaveAsyncTrigger + where TEntity : class { - public class BeforeSaveDelegatingTrigger(Func, CancellationToken, Task> handler) : IBeforeSaveTrigger, IBeforeSaveAsyncTrigger - where TEntity : class - { - readonly Func, CancellationToken, Task> _handler = handler; + readonly Func, CancellationToken, Task> _handler = handler; - public void BeforeSave(ITriggerContext context) => _handler(context, default).Wait(); - public Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => _handler(context, cancellationToken); - } + public void BeforeSave(ITriggerContext context) => _handler(context, default).Wait(); + public Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) => _handler(context, cancellationToken); } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/EventDefinitionBaseStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/EventDefinitionBaseStub.cs index d4ecde3..2922b29 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/EventDefinitionBaseStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/EventDefinitionBaseStub.cs @@ -2,14 +2,13 @@ using Microsoft.EntityFrameworkCore.Diagnostics.Internal; using Microsoft.Extensions.Logging; -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs; + +public class EventDefinitionBaseStub(ILoggingOptions loggingOptions, EventId eventId, LogLevel level, string eventIdCode) : EventDefinitionBase(loggingOptions, eventId, level, eventIdCode) { - public class EventDefinitionBaseStub(ILoggingOptions loggingOptions, EventId eventId, LogLevel level, string eventIdCode) : EventDefinitionBase(loggingOptions, eventId, level, eventIdCode) + public EventDefinitionBaseStub() + : this(new LoggingOptions(), new EventId(), default, "test") { - public EventDefinitionBaseStub() - : this(new LoggingOptions(), new EventId(), default, "test") - { - } } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/OptionsSnapshotStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/OptionsSnapshotStub.cs index 2461d04..e439698 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/OptionsSnapshotStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/OptionsSnapshotStub.cs @@ -1,12 +1,11 @@ using Microsoft.Extensions.Options; -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs; + +public class OptionsSnapshotStub : IOptionsSnapshot + where TOptions : class, new() { - public class OptionsSnapshotStub : IOptionsSnapshot - where TOptions : class, new() - { - public TOptions Value => Activator.CreateInstance(); + public TOptions Value => Activator.CreateInstance(); - public TOptions Get(string name) => Activator.CreateInstance(); - } + public TOptions Get(string name) => Activator.CreateInstance(); } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerContextStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerContextStub.cs index a4c0f2a..5ab0147 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerContextStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerContextStub.cs @@ -1,12 +1,11 @@ -namespace EntityFrameworkCore.Triggered.Tests.Stubs -{ - public class TriggerContextStub : ITriggerContext - where TEntity : class +namespace EntityFrameworkCore.Triggered.Tests.Stubs; + +public class TriggerContextStub : ITriggerContext + where TEntity : class - { - public ChangeType ChangeType { get; set; } - public TEntity Entity { get; set; } - public TEntity UnmodifiedEntity { get; set; } - public IDictionary Items { get; set; } - } +{ + public ChangeType ChangeType { get; set; } + public TEntity Entity { get; set; } + public TEntity UnmodifiedEntity { get; set; } + public IDictionary Items { get; set; } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs index 66f1f17..f9b45aa 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerDiscoveryServiceStub.cs @@ -2,19 +2,18 @@ using EntityFrameworkCore.Triggered.Internal.Descriptors; using Microsoft.Extensions.DependencyInjection; -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs; + +public class TriggerDiscoveryServiceStub : ITriggerDiscoveryService { - public class TriggerDiscoveryServiceStub : ITriggerDiscoveryService - { - public IEnumerable DiscoverAsyncTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) - => []; + public IEnumerable DiscoverAsyncTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) + => []; - public IEnumerable DiscoverTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) - => []; + public IEnumerable DiscoverTriggers(Type openTriggerType, Type entityType, Func triggerTypeDescriptorFactory) + => []; - public IEnumerable DiscoverTriggers() - => []; + public IEnumerable DiscoverTriggers() + => []; - public IServiceProvider ServiceProvider { get; set; } = new ServiceCollection().BuildServiceProvider(); - } + public IServiceProvider ServiceProvider { get; set; } = new ServiceCollection().BuildServiceProvider(); } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs index 0d43ea3..a969abd 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceProviderAccessorStub.cs @@ -1,9 +1,8 @@ -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs; + +public class TriggerServiceProviderAccessorStub(IServiceProvider serviceProvider) : ITriggerServiceProviderAccessor { - public class TriggerServiceProviderAccessorStub(IServiceProvider serviceProvider) : ITriggerServiceProviderAccessor - { - readonly IServiceProvider _serviceProvider = serviceProvider; + readonly IServiceProvider _serviceProvider = serviceProvider; - public IServiceProvider GetTriggerServiceProvider() => _serviceProvider; - } + public IServiceProvider GetTriggerServiceProvider() => _serviceProvider; } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceStub.cs index 968e28e..d0b77c9 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerServiceStub.cs @@ -1,26 +1,25 @@ using Microsoft.EntityFrameworkCore; -namespace EntityFrameworkCore.Triggered.Tests.Stubs -{ - public class TriggerServiceStub : ITriggerService - { - public int CreateSessionCalls; - public IServiceProvider ServiceProvider; - public TriggerSessionStub LastSession; +namespace EntityFrameworkCore.Triggered.Tests.Stubs; - public ITriggerSession Current { get; set; } +public class TriggerServiceStub : ITriggerService +{ + public int CreateSessionCalls; + public IServiceProvider ServiceProvider; + public TriggerSessionStub LastSession; - public TriggerSessionConfiguration Configuration { get; set; } + public ITriggerSession Current { get; set; } - public ITriggerSession CreateSession(DbContext context, IServiceProvider serviceProvider) - { - CreateSessionCalls += 1; - ServiceProvider = serviceProvider; - LastSession = new TriggerSessionStub(); - Current = LastSession; - return LastSession; - } + public TriggerSessionConfiguration Configuration { get; set; } - public ITriggerSession CreateSession(DbContext context, TriggerSessionConfiguration configuration, IServiceProvider serviceProvider = null) => throw new NotImplementedException(); + public ITriggerSession CreateSession(DbContext context, IServiceProvider serviceProvider) + { + CreateSessionCalls += 1; + ServiceProvider = serviceProvider; + LastSession = new TriggerSessionStub(); + Current = LastSession; + return LastSession; } + + public ITriggerSession CreateSession(DbContext context, TriggerSessionConfiguration configuration, IServiceProvider serviceProvider = null) => throw new NotImplementedException(); } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs index e49ffae..202dd5d 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerSessionStub.cs @@ -1,113 +1,112 @@ -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs; + +public class TriggerSessionStub : ITriggerSession { - public class TriggerSessionStub : ITriggerSession + public int RaiseBeforeSaveStartingTriggersCalls { get; set; } + public int RaiseBeforeSaveStartingAsyncTriggersCalls { get; set; } + public int RaiseBeforeSaveTriggersCalls { get; set; } + public int RaiseBeforeSaveAsyncTriggersCalls { get; set; } + public int RaiseBeforeSaveCompletingTriggersCalls { get; set; } + public int RaiseBeforeSaveCompletingAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveStartingTriggersCalls { get; set; } + public int RaiseAfterSaveStartingAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveTriggersCalls { get; set; } + public int RaiseAfterSaveAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveCompletedTriggersCalls { get; set; } + public int RaiseAfterSaveCompletedAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveFailedStartingTriggersCalls { get; set; } + public int RaiseAfterSaveFailedStartingAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveFailedTriggersCalls { get; set; } + public int RaiseAfterSaveFailedAsyncTriggersCalls { get; set; } + public int RaiseAfterSaveFailedCompletedTriggersCalls { get; set; } + public int RaiseAfterSaveFailedCompletedAsyncTriggersCalls { get; set; } + public int CaptureDiscoveredChangesCalls { get; set; } + public int DiscoverChangesCalls { get; set; } + public int DisposeCalls { get; set; } + + public void CaptureDiscoveredChanges() => CaptureDiscoveredChangesCalls += 1; + + public void DiscoverChanges() => DiscoverChangesCalls += 1; + + public void Dispose() => DisposeCalls += 1; + + public void RaiseAfterSaveFailedStartingTriggers(Exception exception) => RaiseAfterSaveFailedStartingTriggersCalls += 1; + + public Task RaiseAfterSaveFailedStartingAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) + { + RaiseAfterSaveFailedStartingAsyncTriggersCalls += 1; + return Task.CompletedTask; + } + + public void RaiseAfterSaveFailedTriggers(Exception exception) => RaiseAfterSaveFailedTriggersCalls += 1; + + public Task RaiseAfterSaveFailedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) + { + RaiseAfterSaveFailedAsyncTriggersCalls += 1; + return Task.CompletedTask; + } + + public void RaiseAfterSaveFailedCompletedTriggers(Exception exception) => RaiseAfterSaveFailedCompletedTriggersCalls += 1; + + public Task RaiseAfterSaveFailedCompletedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) + { + RaiseAfterSaveFailedCompletedAsyncTriggersCalls += 1; + return Task.CompletedTask; + } + + public void RaiseBeforeSaveStartingTriggers() => RaiseBeforeSaveStartingTriggersCalls += 1; + + public Task RaiseBeforeSaveStartingAsyncTriggers(CancellationToken cancellationToken = default) + { + RaiseBeforeSaveStartingAsyncTriggersCalls += 1; + return Task.CompletedTask; + } + + public void RaiseBeforeSaveTriggers() => RaiseBeforeSaveTriggersCalls += 1; + + public Task RaiseBeforeSaveAsyncTriggers(CancellationToken cancellationToken = default) + { + RaiseBeforeSaveAsyncTriggersCalls += 1; + return Task.CompletedTask; + } + + public void RaiseBeforeSaveCompletedTriggers() => RaiseBeforeSaveCompletingTriggersCalls += 1; + + public Task RaiseBeforeSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default) + { + RaiseBeforeSaveCompletingAsyncTriggersCalls += 1; + return Task.CompletedTask; + } + + public void RaiseAfterSaveStartingTriggers() => RaiseAfterSaveStartingTriggersCalls += 1; + + public Task RaiseAfterSaveStartingAsyncTriggers(CancellationToken cancellationToken = default) + { + RaiseAfterSaveStartingAsyncTriggersCalls += 1; + return Task.CompletedTask; + } + + public void RaiseAfterSaveTriggers() => RaiseAfterSaveTriggersCalls += 1; + + public Task RaiseAfterSaveAsyncTriggers(CancellationToken cancellationToken = default) + { + RaiseAfterSaveAsyncTriggersCalls += 1; + return Task.CompletedTask; + } + + public void RaiseAfterSaveCompletedTriggers() => RaiseAfterSaveCompletedTriggersCalls += 1; + + public Task RaiseAfterSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default) + { + RaiseAfterSaveCompletedAsyncTriggersCalls += 1; + return Task.CompletedTask; + } + + public void RaiseBeforeSaveTriggers(bool skipDetectedChanges = false) => RaiseBeforeSaveTriggersCalls += 1; + + public Task RaiseBeforeSaveAsyncTriggers(bool skipDetectedChanges = false, CancellationToken cancellationToken = default) { - public int RaiseBeforeSaveStartingTriggersCalls { get; set; } - public int RaiseBeforeSaveStartingAsyncTriggersCalls { get; set; } - public int RaiseBeforeSaveTriggersCalls { get; set; } - public int RaiseBeforeSaveAsyncTriggersCalls { get; set; } - public int RaiseBeforeSaveCompletingTriggersCalls { get; set; } - public int RaiseBeforeSaveCompletingAsyncTriggersCalls { get; set; } - public int RaiseAfterSaveStartingTriggersCalls { get; set; } - public int RaiseAfterSaveStartingAsyncTriggersCalls { get; set; } - public int RaiseAfterSaveTriggersCalls { get; set; } - public int RaiseAfterSaveAsyncTriggersCalls { get; set; } - public int RaiseAfterSaveCompletedTriggersCalls { get; set; } - public int RaiseAfterSaveCompletedAsyncTriggersCalls { get; set; } - public int RaiseAfterSaveFailedStartingTriggersCalls { get; set; } - public int RaiseAfterSaveFailedStartingAsyncTriggersCalls { get; set; } - public int RaiseAfterSaveFailedTriggersCalls { get; set; } - public int RaiseAfterSaveFailedAsyncTriggersCalls { get; set; } - public int RaiseAfterSaveFailedCompletedTriggersCalls { get; set; } - public int RaiseAfterSaveFailedCompletedAsyncTriggersCalls { get; set; } - public int CaptureDiscoveredChangesCalls { get; set; } - public int DiscoverChangesCalls { get; set; } - public int DisposeCalls { get; set; } - - public void CaptureDiscoveredChanges() => CaptureDiscoveredChangesCalls += 1; - - public void DiscoverChanges() => DiscoverChangesCalls += 1; - - public void Dispose() => DisposeCalls += 1; - - public void RaiseAfterSaveFailedStartingTriggers(Exception exception) => RaiseAfterSaveFailedStartingTriggersCalls += 1; - - public Task RaiseAfterSaveFailedStartingAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) - { - RaiseAfterSaveFailedStartingAsyncTriggersCalls += 1; - return Task.CompletedTask; - } - - public void RaiseAfterSaveFailedTriggers(Exception exception) => RaiseAfterSaveFailedTriggersCalls += 1; - - public Task RaiseAfterSaveFailedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) - { - RaiseAfterSaveFailedAsyncTriggersCalls += 1; - return Task.CompletedTask; - } - - public void RaiseAfterSaveFailedCompletedTriggers(Exception exception) => RaiseAfterSaveFailedCompletedTriggersCalls += 1; - - public Task RaiseAfterSaveFailedCompletedAsyncTriggers(Exception exception, CancellationToken cancellationToken = default) - { - RaiseAfterSaveFailedCompletedAsyncTriggersCalls += 1; - return Task.CompletedTask; - } - - public void RaiseBeforeSaveStartingTriggers() => RaiseBeforeSaveStartingTriggersCalls += 1; - - public Task RaiseBeforeSaveStartingAsyncTriggers(CancellationToken cancellationToken = default) - { - RaiseBeforeSaveStartingAsyncTriggersCalls += 1; - return Task.CompletedTask; - } - - public void RaiseBeforeSaveTriggers() => RaiseBeforeSaveTriggersCalls += 1; - - public Task RaiseBeforeSaveAsyncTriggers(CancellationToken cancellationToken = default) - { - RaiseBeforeSaveAsyncTriggersCalls += 1; - return Task.CompletedTask; - } - - public void RaiseBeforeSaveCompletedTriggers() => RaiseBeforeSaveCompletingTriggersCalls += 1; - - public Task RaiseBeforeSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default) - { - RaiseBeforeSaveCompletingAsyncTriggersCalls += 1; - return Task.CompletedTask; - } - - public void RaiseAfterSaveStartingTriggers() => RaiseAfterSaveStartingTriggersCalls += 1; - - public Task RaiseAfterSaveStartingAsyncTriggers(CancellationToken cancellationToken = default) - { - RaiseAfterSaveStartingAsyncTriggersCalls += 1; - return Task.CompletedTask; - } - - public void RaiseAfterSaveTriggers() => RaiseAfterSaveTriggersCalls += 1; - - public Task RaiseAfterSaveAsyncTriggers(CancellationToken cancellationToken = default) - { - RaiseAfterSaveAsyncTriggersCalls += 1; - return Task.CompletedTask; - } - - public void RaiseAfterSaveCompletedTriggers() => RaiseAfterSaveCompletedTriggersCalls += 1; - - public Task RaiseAfterSaveCompletedAsyncTriggers(CancellationToken cancellationToken = default) - { - RaiseAfterSaveCompletedAsyncTriggersCalls += 1; - return Task.CompletedTask; - } - - public void RaiseBeforeSaveTriggers(bool skipDetectedChanges = false) => RaiseBeforeSaveTriggersCalls += 1; - - public Task RaiseBeforeSaveAsyncTriggers(bool skipDetectedChanges = false, CancellationToken cancellationToken = default) - { - RaiseBeforeSaveAsyncTriggersCalls += 1; - return Task.CompletedTask; - } + RaiseBeforeSaveAsyncTriggersCalls += 1; + return Task.CompletedTask; } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs index a2d1f69..93ceccd 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/Stubs/TriggerStub.cs @@ -1,74 +1,73 @@ -namespace EntityFrameworkCore.Triggered.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Tests.Stubs; + +public class TriggerStub : + IBeforeSaveTrigger, + IBeforeSaveAsyncTrigger, + IAfterSaveTrigger, + IAfterSaveAsyncTrigger, + IAfterSaveFailedTrigger, + IAfterSaveFailedAsyncTrigger, + ITriggerPriority + where TEntity : class { - public class TriggerStub : - IBeforeSaveTrigger, - IBeforeSaveAsyncTrigger, - IAfterSaveTrigger, - IAfterSaveAsyncTrigger, - IAfterSaveFailedTrigger, - IAfterSaveFailedAsyncTrigger, - ITriggerPriority - where TEntity : class - { - public ICollection> BeforeSaveInvocations { get; } = []; - public ICollection> BeforeSaveAsyncInvocations { get; } = []; - public ICollection> AfterSaveInvocations { get; } = []; - public ICollection> AfterSaveAsyncInvocations { get; } = []; - public ICollection<(ITriggerContext context, Exception exception)> AfterSaveFailedInvocations { get; } = new List<(ITriggerContext, Exception)>(); - public ICollection<(ITriggerContext context, Exception exception)> AfterSaveFailedAsyncInvocations { get; } = new List<(ITriggerContext, Exception)>(); + public ICollection> BeforeSaveInvocations { get; } = []; + public ICollection> BeforeSaveAsyncInvocations { get; } = []; + public ICollection> AfterSaveInvocations { get; } = []; + public ICollection> AfterSaveAsyncInvocations { get; } = []; + public ICollection<(ITriggerContext context, Exception exception)> AfterSaveFailedInvocations { get; } = new List<(ITriggerContext, Exception)>(); + public ICollection<(ITriggerContext context, Exception exception)> AfterSaveFailedAsyncInvocations { get; } = new List<(ITriggerContext, Exception)>(); - public int Priority { get; set; } + public int Priority { get; set; } - public Action> BeforeSaveHandler { get; set; } - public Func, CancellationToken, Task> BeforeSaveAsyncHandler { get; set; } - public Action> AfterSaveHandler { get; set; } - public Func, CancellationToken, Task> AfterSaveAsyncHandler { get; set; } - public Action, Exception> AfterSaveFailedHandler { get; set; } - public Func, Exception, CancellationToken, Task> AfterSaveFailedAsyncHandler { get; set; } + public Action> BeforeSaveHandler { get; set; } + public Func, CancellationToken, Task> BeforeSaveAsyncHandler { get; set; } + public Action> AfterSaveHandler { get; set; } + public Func, CancellationToken, Task> AfterSaveAsyncHandler { get; set; } + public Action, Exception> AfterSaveFailedHandler { get; set; } + public Func, Exception, CancellationToken, Task> AfterSaveFailedAsyncHandler { get; set; } - public TriggerStub() - { + public TriggerStub() + { - } + } - public void BeforeSave(ITriggerContext context) - { - BeforeSaveInvocations.Add(context); - BeforeSaveHandler?.Invoke(context); - } + public void BeforeSave(ITriggerContext context) + { + BeforeSaveInvocations.Add(context); + BeforeSaveHandler?.Invoke(context); + } - public Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) - { - BeforeSaveAsyncInvocations.Add(context); - BeforeSaveAsyncHandler?.Invoke(context, cancellationToken); - return Task.CompletedTask; - } + public Task BeforeSaveAsync(ITriggerContext context, CancellationToken cancellationToken) + { + BeforeSaveAsyncInvocations.Add(context); + BeforeSaveAsyncHandler?.Invoke(context, cancellationToken); + return Task.CompletedTask; + } - public void AfterSave(ITriggerContext context) - { - AfterSaveInvocations.Add(context); - AfterSaveHandler?.Invoke(context); - } + public void AfterSave(ITriggerContext context) + { + AfterSaveInvocations.Add(context); + AfterSaveHandler?.Invoke(context); + } - public Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) - { - AfterSaveAsyncInvocations.Add(context); - AfterSaveAsyncHandler?.Invoke(context, cancellationToken); - return Task.CompletedTask; - } + public Task AfterSaveAsync(ITriggerContext context, CancellationToken cancellationToken) + { + AfterSaveAsyncInvocations.Add(context); + AfterSaveAsyncHandler?.Invoke(context, cancellationToken); + return Task.CompletedTask; + } - public void AfterSaveFailed(ITriggerContext context, Exception exception) - { - AfterSaveFailedInvocations.Add((context, exception)); - AfterSaveFailedHandler?.Invoke(context, exception); - } + public void AfterSaveFailed(ITriggerContext context, Exception exception) + { + AfterSaveFailedInvocations.Add((context, exception)); + AfterSaveFailedHandler?.Invoke(context, exception); + } - public Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken) - { - AfterSaveFailedAsyncInvocations.Add((context, exception)); - AfterSaveFailedAsyncHandler?.Invoke(context, exception, cancellationToken); - return Task.CompletedTask; - } + public Task AfterSaveFailedAsync(ITriggerContext context, Exception exception, CancellationToken cancellationToken) + { + AfterSaveFailedAsyncInvocations.Add((context, exception)); + AfterSaveFailedAsyncHandler?.Invoke(context, exception, cancellationToken); + return Task.CompletedTask; } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggerContextTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggerContextTests.cs index 326e7b9..acb0b84 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggerContextTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggerContextTests.cs @@ -2,119 +2,118 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests.Internal +namespace EntityFrameworkCore.Triggered.Tests.Internal; + +public class TriggerContextTests { - public class TriggerContextTests + class TestModel { public int Id { get; set; } public string Name { get; set; } } + + class TestDbContext : DbContext { - class TestModel { public int Id { get; set; } public string Name { get; set; } } + public DbSet TestModels { get; set; } - class TestDbContext : DbContext + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - public DbSet TestModels { get; set; } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - } + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); } + } - [Fact] - public void UnmodifiedEntity_WhenTypeAdded_IsEmpty() - { - using var dbContext = new TestDbContext(); - var sample1 = new TestModel() { Id = 1 }; - var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Added, new()); + [Fact] + public void UnmodifiedEntity_WhenTypeAdded_IsEmpty() + { + using var dbContext = new TestDbContext(); + var sample1 = new TestModel() { Id = 1 }; + var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Added, new()); - Assert.Null(subject.UnmodifiedEntity); - } + Assert.Null(subject.UnmodifiedEntity); + } - [Fact] - public void UnmodifiedEntity_WhenTypeDeleted_IsNotEmpty() - { - using var dbContext = new TestDbContext(); - var sample1 = new TestModel(); - var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Deleted, new()); + [Fact] + public void UnmodifiedEntity_WhenTypeDeleted_IsNotEmpty() + { + using var dbContext = new TestDbContext(); + var sample1 = new TestModel(); + var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Deleted, new()); - Assert.NotNull(subject.UnmodifiedEntity); - } + Assert.NotNull(subject.UnmodifiedEntity); + } - [Fact] - public void UnmodifiedEntity_WhenTypeModified_IsNotEmpty() - { - using var dbContext = new TestDbContext(); - var sample1 = new TestModel(); - var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Modified, new()); + [Fact] + public void UnmodifiedEntity_WhenTypeModified_IsNotEmpty() + { + using var dbContext = new TestDbContext(); + var sample1 = new TestModel(); + var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Modified, new()); - Assert.NotNull(subject.UnmodifiedEntity); - } + Assert.NotNull(subject.UnmodifiedEntity); + } - [Fact] - public void UnmodifiedEntity_WhenTypeModified_HoldsUnmodifiedStateBeforeSaveChanges() - { - using var dbContext = new TestDbContext(); - var sample1 = new TestModel { Name = "test1" }; - dbContext.Add(sample1); - dbContext.SaveChanges(); + [Fact] + public void UnmodifiedEntity_WhenTypeModified_HoldsUnmodifiedStateBeforeSaveChanges() + { + using var dbContext = new TestDbContext(); + var sample1 = new TestModel { Name = "test1" }; + dbContext.Add(sample1); + dbContext.SaveChanges(); - var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Modified, new()); - sample1.Name = "test2"; + var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Modified, new()); + sample1.Name = "test2"; - Assert.NotNull(subject.UnmodifiedEntity); - Assert.Equal("test1", subject.UnmodifiedEntity.Name); + Assert.NotNull(subject.UnmodifiedEntity); + Assert.Equal("test1", subject.UnmodifiedEntity.Name); - dbContext.SaveChanges(); - } + dbContext.SaveChanges(); + } - [Fact] - public void UnmodifiedEntity_WhenTypeModified_HoldsUnmodifiedStateAfterSaveChanges() - { - using var dbContext = new TestDbContext(); - var sample1 = new TestModel { Name = "test1" }; - dbContext.Add(sample1); - dbContext.SaveChanges(); + [Fact] + public void UnmodifiedEntity_WhenTypeModified_HoldsUnmodifiedStateAfterSaveChanges() + { + using var dbContext = new TestDbContext(); + var sample1 = new TestModel { Name = "test1" }; + dbContext.Add(sample1); + dbContext.SaveChanges(); - var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues.Clone(), ChangeType.Modified, new()); - sample1.Name = "test2"; + var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues.Clone(), ChangeType.Modified, new()); + sample1.Name = "test2"; - dbContext.SaveChanges(); + dbContext.SaveChanges(); - Assert.NotNull(subject.UnmodifiedEntity); - Assert.Equal("test1", subject.UnmodifiedEntity.Name); - } + Assert.NotNull(subject.UnmodifiedEntity); + Assert.Equal("test1", subject.UnmodifiedEntity.Name); + } - [Fact] - public void Entity_IsNeverEmpty() - { - using var dbContext = new TestDbContext(); - var sample1 = new TestModel(); - var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, default, new()); + [Fact] + public void Entity_IsNeverEmpty() + { + using var dbContext = new TestDbContext(); + var sample1 = new TestModel(); + var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, default, new()); - Assert.NotNull(subject.Entity); - } + Assert.NotNull(subject.Entity); + } - [Fact] - public void Type_IsNotEmpty() - { - using var dbContext = new TestDbContext(); - var sample1 = new TestModel(); - var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Modified, new()); + [Fact] + public void Type_IsNotEmpty() + { + using var dbContext = new TestDbContext(); + var sample1 = new TestModel(); + var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Modified, new()); - Assert.Equal(ChangeType.Modified, subject.ChangeType); - } + Assert.Equal(ChangeType.Modified, subject.ChangeType); + } - [Fact] - public void EntityBag_ConsistentlyReturnsTheSameInstance() - { - using var dbContext = new TestDbContext(); - var sample1 = new TestModel(); - var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Modified, new()); + [Fact] + public void EntityBag_ConsistentlyReturnsTheSameInstance() + { + using var dbContext = new TestDbContext(); + var sample1 = new TestModel(); + var subject = new TriggerContext(dbContext.Entry(sample1), dbContext.Entry(sample1).OriginalValues, ChangeType.Modified, new()); - var expectedInstance = subject.Items; - Assert.Equal(expectedInstance, subject.Items); - } + var expectedInstance = subject.Items; + Assert.Equal(expectedInstance, subject.Items); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs index b9c8067..15d8590 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceApplicationDependenciesTests.cs @@ -4,124 +4,156 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests -{ - public class TriggerServiceApplicationDependenciesTests - { - class TestModel { public int Id { get; set; } } +namespace EntityFrameworkCore.Triggered.Tests; - class TestDbContext(DbContextOptions options) : DbContext(options) - { - public DbSet TestModels { get; set; } - } +public class TriggerServiceApplicationDependenciesTests +{ + class TestModel { public int Id { get; set; } } - [Fact] - public void ScopedTriggers_NoScopedApplicationServiceProvider_ForDbContext_DoesNotLeak() - { - var applicationServiceProvider = new ServiceCollection() - .AddDbContext(options => { - options.UseInMemoryDatabase("Test"); - options.UseTriggers(); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .AddScoped, Stubs.TriggerStub>() - .BuildServiceProvider(); - - void SimulateRequest() - { - using var serviceScope = applicationServiceProvider.CreateScope(); - var dbContext = serviceScope.ServiceProvider.GetRequiredService(); - var triggerStub = serviceScope.ServiceProvider.GetRequiredService>() as TriggerStub; - Assert.Empty(triggerStub.BeforeSaveInvocations); - - dbContext.Add(new TestModel { }); - dbContext.SaveChanges(); - } - - SimulateRequest(); - SimulateRequest(); - } + class TestDbContext(DbContextOptions options) : DbContext(options) + { + public DbSet TestModels { get; set; } + } - [Fact] - public void ScopedTriggers_NoScopedApplicationServiceProvider_ForPooledDbContext() + [Fact] + public void ScopedTriggers_NoScopedApplicationServiceProvider_ForDbContext_DoesNotLeak() + { + var applicationServiceProvider = new ServiceCollection() + .AddDbContext(options => { + options.UseInMemoryDatabase("Test"); + options.UseTriggers(); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .AddScoped, Stubs.TriggerStub>() + .BuildServiceProvider(); + + void SimulateRequest() { - var applicationServiceProvider = new ServiceCollection() - .AddDbContextPool(options => { - options.UseInMemoryDatabase("Test"); - options.UseTriggers(); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .AddScoped, TriggerStub>() - .BuildServiceProvider(); - using var serviceScope = applicationServiceProvider.CreateScope(); var dbContext = serviceScope.ServiceProvider.GetRequiredService(); + var triggerStub = serviceScope.ServiceProvider.GetRequiredService>() as TriggerStub; + Assert.Empty(triggerStub.BeforeSaveInvocations); dbContext.Add(new TestModel { }); dbContext.SaveChanges(); + } - var triggerStub = serviceScope.ServiceProvider.GetRequiredService>() as TriggerStub; + SimulateRequest(); + SimulateRequest(); + } - Assert.Empty(triggerStub.BeforeSaveInvocations); + [Fact] + public void ScopedTriggers_NoScopedApplicationServiceProvider_ForPooledDbContext() + { + var applicationServiceProvider = new ServiceCollection() + .AddDbContextPool(options => { + options.UseInMemoryDatabase("Test"); + options.UseTriggers(); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .AddScoped, TriggerStub>() + .BuildServiceProvider(); - } + using var serviceScope = applicationServiceProvider.CreateScope(); + var dbContext = serviceScope.ServiceProvider.GetRequiredService(); - [Fact] - public void ScopedTriggers_WithScopedApplicationServiceProvider_ForDbContext() - { - IServiceProvider scopedServiceProvider = null; - - var applicationServiceProvider = new ServiceCollection() - .AddDbContext(options => { - options.UseInMemoryDatabase("Test"); - options.UseTriggers(triggerOptions => { - triggerOptions.UseApplicationScopedServiceProviderAccessor(_ => scopedServiceProvider); - }); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .AddScoped, Stubs.TriggerStub>() - .BuildServiceProvider(); + dbContext.Add(new TestModel { }); + dbContext.SaveChanges(); - using var serviceScope = applicationServiceProvider.CreateScope(); - scopedServiceProvider = serviceScope.ServiceProvider; - var dbContext = serviceScope.ServiceProvider.GetRequiredService(); + var triggerStub = serviceScope.ServiceProvider.GetRequiredService>() as TriggerStub; - dbContext.Add(new TestModel { }); - dbContext.SaveChanges(); + Assert.Empty(triggerStub.BeforeSaveInvocations); - var triggerStub = scopedServiceProvider.GetRequiredService>() as TriggerStub; + } - Assert.Single(triggerStub.BeforeSaveInvocations); - } + [Fact] + public void ScopedTriggers_WithScopedApplicationServiceProvider_ForDbContext() + { + IServiceProvider scopedServiceProvider = null; + + var applicationServiceProvider = new ServiceCollection() + .AddDbContext(options => { + options.UseInMemoryDatabase("Test"); + options.UseTriggers(triggerOptions => { + triggerOptions.UseApplicationScopedServiceProviderAccessor(_ => scopedServiceProvider); + }); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .AddScoped, Stubs.TriggerStub>() + .BuildServiceProvider(); + + using var serviceScope = applicationServiceProvider.CreateScope(); + scopedServiceProvider = serviceScope.ServiceProvider; + var dbContext = serviceScope.ServiceProvider.GetRequiredService(); + + dbContext.Add(new TestModel { }); + dbContext.SaveChanges(); + + var triggerStub = scopedServiceProvider.GetRequiredService>() as TriggerStub; + + Assert.Single(triggerStub.BeforeSaveInvocations); + } - [Fact] - public void ScopedTriggers_WithScopedApplicationServiceProvider_ForPooledDbContext() - { - IServiceProvider scopedServiceProvider = null; - - var applicationServiceProvider = new ServiceCollection() - .AddDbContextPool(options => { - options.UseInMemoryDatabase("Test"); - options.UseTriggers(triggerOptions => { - triggerOptions.UseApplicationScopedServiceProviderAccessor(_ => scopedServiceProvider); - }); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .AddScoped, TriggerStub>() - .BuildServiceProvider(); + [Fact] + public void ScopedTriggers_WithScopedApplicationServiceProvider_ForPooledDbContext() + { + IServiceProvider scopedServiceProvider = null; + + var applicationServiceProvider = new ServiceCollection() + .AddDbContextPool(options => { + options.UseInMemoryDatabase("Test"); + options.UseTriggers(triggerOptions => { + triggerOptions.UseApplicationScopedServiceProviderAccessor(_ => scopedServiceProvider); + }); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .AddScoped, TriggerStub>() + .BuildServiceProvider(); + + using var serviceScope = applicationServiceProvider.CreateScope(); + scopedServiceProvider = serviceScope.ServiceProvider; + var dbContext = serviceScope.ServiceProvider.GetRequiredService(); + + dbContext.Add(new TestModel { }); + dbContext.SaveChanges(); + + var triggerStub = scopedServiceProvider.GetRequiredService>() as TriggerStub; + + Assert.Single(triggerStub.BeforeSaveInvocations); + } + [Fact] + public void ScopedTriggers_ForPooledDbContext_DoNotShareServiceProvider() + { + IServiceProvider scopedServiceProvider = null; + + var applicationServiceProvider = new ServiceCollection() + .AddDbContextPool(options => { + options.UseInMemoryDatabase("Test"); + options.UseTriggers(triggerOptions => { + triggerOptions.UseApplicationScopedServiceProviderAccessor(_ => scopedServiceProvider); + }); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .AddScoped, TriggerStub>() + .BuildServiceProvider(); + + void SimulateRequest() + { using var serviceScope = applicationServiceProvider.CreateScope(); scopedServiceProvider = serviceScope.ServiceProvider; - var dbContext = serviceScope.ServiceProvider.GetRequiredService(); + using var dbContext = serviceScope.ServiceProvider.GetRequiredService(); dbContext.Add(new TestModel { }); dbContext.SaveChanges(); @@ -131,40 +163,7 @@ public void ScopedTriggers_WithScopedApplicationServiceProvider_ForPooledDbConte Assert.Single(triggerStub.BeforeSaveInvocations); } - [Fact] - public void ScopedTriggers_ForPooledDbContext_DoNotShareServiceProvider() - { - IServiceProvider scopedServiceProvider = null; - - var applicationServiceProvider = new ServiceCollection() - .AddDbContextPool(options => { - options.UseInMemoryDatabase("Test"); - options.UseTriggers(triggerOptions => { - triggerOptions.UseApplicationScopedServiceProviderAccessor(_ => scopedServiceProvider); - }); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .AddScoped, TriggerStub>() - .BuildServiceProvider(); - - void SimulateRequest() - { - using var serviceScope = applicationServiceProvider.CreateScope(); - scopedServiceProvider = serviceScope.ServiceProvider; - using var dbContext = serviceScope.ServiceProvider.GetRequiredService(); - - dbContext.Add(new TestModel { }); - dbContext.SaveChanges(); - - var triggerStub = scopedServiceProvider.GetRequiredService>() as TriggerStub; - - Assert.Single(triggerStub.BeforeSaveInvocations); - } - - SimulateRequest(); - SimulateRequest(); - } + SimulateRequest(); + SimulateRequest(); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceTests.cs index 2dd851a..04e67d8 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggerServiceTests.cs @@ -5,64 +5,63 @@ using Microsoft.Extensions.Logging; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests +namespace EntityFrameworkCore.Triggered.Tests; + +public class TriggerServiceTests { - public class TriggerServiceTests + public class TestModel { - public class TestModel - { - public int Id { get; set; } - public string Name { get; set; } - } + public int Id { get; set; } + public string Name { get; set; } + } - public class TestDbContext : DbContext + public class TestDbContext : DbContext + { + public TestDbContext() { - public TestDbContext() - { - } + } - public DbSet TestModels { get; set; } + public DbSet TestModels { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - base.OnConfiguring(optionsBuilder); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); - optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - } + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); } + } - [Fact] - public void Current_WithoutSession_ReturnsNull() - { - var subject = new TriggerService(new TriggerDiscoveryServiceStub(), new NoCascadeStrategy(), new LoggerFactory(), new OptionsSnapshotStub()); - Assert.Null(subject.Current); - } + [Fact] + public void Current_WithoutSession_ReturnsNull() + { + var subject = new TriggerService(new TriggerDiscoveryServiceStub(), new NoCascadeStrategy(), new LoggerFactory(), new OptionsSnapshotStub()); + Assert.Null(subject.Current); + } - [Fact] - public void Current_WithSingleSession_ReturnsSession() - { - var subject = new TriggerService(new TriggerDiscoveryServiceStub(), new NoCascadeStrategy(), new LoggerFactory(), new OptionsSnapshotStub()); - var dbContext = new TestDbContext(); + [Fact] + public void Current_WithSingleSession_ReturnsSession() + { + var subject = new TriggerService(new TriggerDiscoveryServiceStub(), new NoCascadeStrategy(), new LoggerFactory(), new OptionsSnapshotStub()); + var dbContext = new TestDbContext(); - var triggerSession = subject.CreateSession(dbContext, null); + var triggerSession = subject.CreateSession(dbContext, null); - Assert.Equal(subject.Current, triggerSession); - } + Assert.Equal(subject.Current, triggerSession); + } - [Fact] - public void Current_WithMultipleSessions_ReturnsLatestSession() - { - var subject = new TriggerService(new TriggerDiscoveryServiceStub(), new NoCascadeStrategy(), new LoggerFactory(), new OptionsSnapshotStub()); - var dbContext = new TestDbContext(); + [Fact] + public void Current_WithMultipleSessions_ReturnsLatestSession() + { + var subject = new TriggerService(new TriggerDiscoveryServiceStub(), new NoCascadeStrategy(), new LoggerFactory(), new OptionsSnapshotStub()); + var dbContext = new TestDbContext(); - subject.CreateSession(dbContext, null); - var triggerSession = subject.CreateSession(dbContext, null); + subject.CreateSession(dbContext, null); + var triggerSession = subject.CreateSession(dbContext, null); - Assert.Equal(subject.Current, triggerSession); - } + Assert.Equal(subject.Current, triggerSession); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs index 1b17f96..ee2ad38 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggerSessionTests.cs @@ -5,515 +5,514 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests +namespace EntityFrameworkCore.Triggered.Tests; + +public class TriggerSessionTests { - public class TriggerSessionTests + public class TestModel + { + public int Id { get; set; } + public string Name { get; set; } + } + + public class TestDbContext : DbContext { - public class TestModel + public TestDbContext(DbContextOptions options) : base(options) { - public int Id { get; set; } - public string Name { get; set; } } - public class TestDbContext : DbContext + public TestDbContext() { - public TestDbContext(DbContextOptions options) : base(options) - { - } - - public TestDbContext() - { - } + } - public TriggerStub TriggerStub { get; } = new TriggerStub(); + public TriggerStub TriggerStub { get; } = new TriggerStub(); - public DbSet TestModels { get; set; } + public DbSet TestModels { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - base.OnConfiguring(optionsBuilder); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); - optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(TriggerStub); - }); - } + optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(TriggerStub); + }); } + } - protected static ITriggerSession CreateSubject(DbContext context) - => context.Database.GetService().CreateSession(context); + protected static ITriggerSession CreateSubject(DbContext context) + => context.Database.GetService().CreateSession(context); - [Fact] - public void RaiseBeforeSaveTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public void RaiseBeforeSaveTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - subject.RaiseBeforeSaveTriggers(); + subject.RaiseBeforeSaveTriggers(); - Assert.Empty(context.TriggerStub.BeforeSaveInvocations); - } + Assert.Empty(context.TriggerStub.BeforeSaveInvocations); + } - [Fact] - public async Task RaiseBeforeSaveAsyncTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public async Task RaiseBeforeSaveAsyncTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - await subject.RaiseBeforeSaveAsyncTriggers(); + await subject.RaiseBeforeSaveAsyncTriggers(); - Assert.Empty(context.TriggerStub.BeforeSaveAsyncInvocations); - } + Assert.Empty(context.TriggerStub.BeforeSaveAsyncInvocations); + } - [Fact] - public void RaiseAfterSaveTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public void RaiseAfterSaveTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - subject.DiscoverChanges(); - subject.RaiseAfterSaveTriggers(); + subject.DiscoverChanges(); + subject.RaiseAfterSaveTriggers(); - Assert.Empty(context.TriggerStub.AfterSaveInvocations); - } + Assert.Empty(context.TriggerStub.AfterSaveInvocations); + } - [Fact] - public async Task RaiseAfterSaveAsyncTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public async Task RaiseAfterSaveAsyncTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - subject.DiscoverChanges(); - await subject.RaiseAfterSaveAsyncTriggers(); + subject.DiscoverChanges(); + await subject.RaiseAfterSaveAsyncTriggers(); - Assert.Empty(context.TriggerStub.AfterSaveAsyncInvocations); - } + Assert.Empty(context.TriggerStub.AfterSaveAsyncInvocations); + } - [Fact] - public void RaiseBeforeSaveTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public void RaiseBeforeSaveTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - subject.RaiseBeforeSaveTriggers(); + subject.RaiseBeforeSaveTriggers(); - Assert.Single(context.TriggerStub.BeforeSaveInvocations); - } + Assert.Single(context.TriggerStub.BeforeSaveInvocations); + } - [Fact] - public async Task RaiseBeforeSaveAsyncTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public async Task RaiseBeforeSaveAsyncTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - await subject.RaiseBeforeSaveAsyncTriggers(); + await subject.RaiseBeforeSaveAsyncTriggers(); - Assert.Single(context.TriggerStub.BeforeSaveAsyncInvocations); - } + Assert.Single(context.TriggerStub.BeforeSaveAsyncInvocations); + } - [Fact] - public void RaiseAfterSaveTriggers_WithoutCallToRaiseBeforeSaveTriggers_Throws() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public void RaiseAfterSaveTriggers_WithoutCallToRaiseBeforeSaveTriggers_Throws() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - Assert.Throws(() => subject.RaiseAfterSaveTriggers()); - } + Assert.Throws(() => subject.RaiseAfterSaveTriggers()); + } - [Fact] - public async Task RaiseAfterSaveAsyncTriggers_WithoutCallToRaiseBeforeSaveTriggers_Throws() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public async Task RaiseAfterSaveAsyncTriggers_WithoutCallToRaiseBeforeSaveTriggers_Throws() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - await Assert.ThrowsAsync(async () => await subject.RaiseAfterSaveAsyncTriggers()); - } + await Assert.ThrowsAsync(async () => await subject.RaiseAfterSaveAsyncTriggers()); + } - [Fact] - public void RaiseAfterSaveTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public void RaiseAfterSaveTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - subject.DiscoverChanges(); - subject.RaiseAfterSaveTriggers(); + subject.DiscoverChanges(); + subject.RaiseAfterSaveTriggers(); - Assert.Single(context.TriggerStub.AfterSaveInvocations); - } + Assert.Single(context.TriggerStub.AfterSaveInvocations); + } - [Fact] - public async Task RaiseAfterSaveAsyncTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public async Task RaiseAfterSaveAsyncTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - subject.DiscoverChanges(); - await subject.RaiseAfterSaveAsyncTriggers(); + subject.DiscoverChanges(); + await subject.RaiseAfterSaveAsyncTriggers(); - Assert.Single(context.TriggerStub.AfterSaveAsyncInvocations); - } + Assert.Single(context.TriggerStub.AfterSaveAsyncInvocations); + } - [Fact] - public async Task RaiseBeforeSaveAsyncTriggers_ThrowsOnCancelledException() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public async Task RaiseBeforeSaveAsyncTriggers_ThrowsOnCancelledException() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - var cancellationTokenSource = new CancellationTokenSource(); - cancellationTokenSource.Cancel(); - await Assert.ThrowsAsync(async () => await subject.RaiseBeforeSaveAsyncTriggers(cancellationTokenSource.Token)); - } + var cancellationTokenSource = new CancellationTokenSource(); + cancellationTokenSource.Cancel(); + await Assert.ThrowsAsync(async () => await subject.RaiseBeforeSaveAsyncTriggers(cancellationTokenSource.Token)); + } - [Fact] - public async Task RaiseAfterSaveAsyncTriggers_ThrowsOnCancelledException() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public async Task RaiseAfterSaveAsyncTriggers_ThrowsOnCancelledException() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - subject.DiscoverChanges(); + subject.DiscoverChanges(); - var cancellationTokenSource = new CancellationTokenSource(); - cancellationTokenSource.Cancel(); + var cancellationTokenSource = new CancellationTokenSource(); + cancellationTokenSource.Cancel(); - await Assert.ThrowsAsync(async () => await subject.RaiseAfterSaveAsyncTriggers(cancellationTokenSource.Token)); - } + await Assert.ThrowsAsync(async () => await subject.RaiseAfterSaveAsyncTriggers(cancellationTokenSource.Token)); + } - [Fact] - public void RaiseBeforeSaveTriggers_CascadingCall_SkipsDiscoveredChanges() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public void RaiseBeforeSaveTriggers_CascadingCall_SkipsDiscoveredChanges() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TriggerStub.BeforeSaveHandler = _ => { - if (context.TriggerStub.BeforeSaveInvocations.Count <= 1) - { - subject.RaiseBeforeSaveTriggers(default); - } - }; + context.TriggerStub.BeforeSaveHandler = _ => { + if (context.TriggerStub.BeforeSaveInvocations.Count <= 1) + { + subject.RaiseBeforeSaveTriggers(default); + } + }; - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - subject.DiscoverChanges(); - subject.RaiseBeforeSaveTriggers(); + subject.DiscoverChanges(); + subject.RaiseBeforeSaveTriggers(); - Assert.NotEmpty(context.TriggerStub.BeforeSaveInvocations); - } + Assert.NotEmpty(context.TriggerStub.BeforeSaveInvocations); + } - [Fact] - public void RaiseBeforeSaveTriggers_SkipDetectedChangesAsTrue_ExcludesDetectedChanges() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public void RaiseBeforeSaveTriggers_SkipDetectedChangesAsTrue_ExcludesDetectedChanges() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - subject.DiscoverChanges(); - subject.RaiseBeforeSaveTriggers(true); + subject.DiscoverChanges(); + subject.RaiseBeforeSaveTriggers(true); - Assert.Empty(context.TriggerStub.BeforeSaveInvocations); - } + Assert.Empty(context.TriggerStub.BeforeSaveInvocations); + } - [Fact] - public void RaiseBeforeSaveTriggers_SkipDetectedChangesAsFalse_IncludesDetectedChanges() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public void RaiseBeforeSaveTriggers_SkipDetectedChangesAsFalse_IncludesDetectedChanges() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - subject.DiscoverChanges(); - subject.RaiseBeforeSaveTriggers(); + subject.DiscoverChanges(); + subject.RaiseBeforeSaveTriggers(); - Assert.NotEmpty(context.TriggerStub.BeforeSaveInvocations); - } + Assert.NotEmpty(context.TriggerStub.BeforeSaveInvocations); + } - [Fact] - public void RaiseBeforeSaveTriggers_MultipleEntities_SortByPriorities() - { - var capturedInvocations = new List<(string, ITriggerContext)>(); + [Fact] + public void RaiseBeforeSaveTriggers_MultipleEntities_SortByPriorities() + { + var capturedInvocations = new List<(string, ITriggerContext)>(); - var earlyTrigger = new TriggerStub { - Priority = CommonTriggerPriority.Early, - BeforeSaveHandler = context => { - capturedInvocations.Add(("Early", context)); - } - }; + var earlyTrigger = new TriggerStub { + Priority = CommonTriggerPriority.Early, + BeforeSaveHandler = context => { + capturedInvocations.Add(("Early", context)); + } + }; - var lateTrigger = new TriggerStub { - Priority = CommonTriggerPriority.Late, - BeforeSaveHandler = context => { - capturedInvocations.Add(("Late", context)); - } - }; - - var serviceProvider = new ServiceCollection() - .AddSingleton>(lateTrigger) - .AddSingleton>(earlyTrigger) - .AddTriggeredDbContext(options => { - options.UseInMemoryDatabase("Test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .BuildServiceProvider(); - - var scope = serviceProvider.CreateScope(); - var dbContext = scope.ServiceProvider.GetRequiredService(); - var subject = CreateSubject(dbContext); - - dbContext.TestModels.Add(new TestModel { Id = 1 }); - dbContext.TestModels.Add(new TestModel { Id = 2 }); + var lateTrigger = new TriggerStub { + Priority = CommonTriggerPriority.Late, + BeforeSaveHandler = context => { + capturedInvocations.Add(("Late", context)); + } + }; + + var serviceProvider = new ServiceCollection() + .AddSingleton>(lateTrigger) + .AddSingleton>(earlyTrigger) + .AddTriggeredDbContext(options => { + options.UseInMemoryDatabase("Test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .BuildServiceProvider(); - subject.RaiseBeforeSaveTriggers(); + var scope = serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + var subject = CreateSubject(dbContext); - Assert.Equal(4, capturedInvocations.Count); - Assert.Equal("Early", capturedInvocations[0].Item1); - Assert.Equal("Early", capturedInvocations[1].Item1); - Assert.Equal("Late", capturedInvocations[2].Item1); - Assert.Equal("Late", capturedInvocations[3].Item1); - } + dbContext.TestModels.Add(new TestModel { Id = 1 }); + dbContext.TestModels.Add(new TestModel { Id = 2 }); + subject.RaiseBeforeSaveTriggers(); - [Fact] - public void RaiseBeforeSaveTriggers_CascadingAdd_RaisesSubsequentTriggers() - { - TestDbContext dbContext = null; - - var trigger = new TriggerStub { - Priority = CommonTriggerPriority.Early, - BeforeSaveHandler = context => { - if (context.Entity.Id == 1) - { - dbContext.TestModels.Add(new TestModel { Id = 2 }); - } + Assert.Equal(4, capturedInvocations.Count); + Assert.Equal("Early", capturedInvocations[0].Item1); + Assert.Equal("Early", capturedInvocations[1].Item1); + Assert.Equal("Late", capturedInvocations[2].Item1); + Assert.Equal("Late", capturedInvocations[3].Item1); + } + + + [Fact] + public void RaiseBeforeSaveTriggers_CascadingAdd_RaisesSubsequentTriggers() + { + TestDbContext dbContext = null; + + var trigger = new TriggerStub { + Priority = CommonTriggerPriority.Early, + BeforeSaveHandler = context => { + if (context.Entity.Id == 1) + { + dbContext.TestModels.Add(new TestModel { Id = 2 }); } - }; + } + }; - var serviceProvider = new ServiceCollection() - .AddSingleton>(trigger) - .AddTriggeredDbContext(options => { - options.UseInMemoryDatabase("Test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddSingleton>(trigger) + .AddTriggeredDbContext(options => { + options.UseInMemoryDatabase("Test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .BuildServiceProvider(); - var scope = serviceProvider.CreateScope(); - dbContext = scope.ServiceProvider.GetRequiredService(); - var subject = CreateSubject(dbContext); + var scope = serviceProvider.CreateScope(); + dbContext = scope.ServiceProvider.GetRequiredService(); + var subject = CreateSubject(dbContext); - dbContext.TestModels.Add(new TestModel { Id = 1 }); + dbContext.TestModels.Add(new TestModel { Id = 1 }); - subject.RaiseBeforeSaveTriggers(); + subject.RaiseBeforeSaveTriggers(); - Assert.Equal(2, trigger.BeforeSaveInvocations.Count); - } + Assert.Equal(2, trigger.BeforeSaveInvocations.Count); + } - [Fact] - public void RaiseAfterSaveFailedTriggers_OnException_RaisesSubsequentTriggers() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public void RaiseAfterSaveFailedTriggers_OnException_RaisesSubsequentTriggers() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - subject.DiscoverChanges(); - subject.RaiseAfterSaveFailedTriggers(new Exception()); + subject.DiscoverChanges(); + subject.RaiseAfterSaveFailedTriggers(new Exception()); - Assert.Single(context.TriggerStub.AfterSaveFailedInvocations); - } + Assert.Single(context.TriggerStub.AfterSaveFailedInvocations); + } - [Fact] - public async Task RaiseAfterSaveFailedAsyncTriggers_OnException_RaisesSubsequentTriggers() - { - using var context = new TestDbContext(); - var subject = CreateSubject(context); + [Fact] + public async Task RaiseAfterSaveFailedAsyncTriggers_OnException_RaisesSubsequentTriggers() + { + using var context = new TestDbContext(); + var subject = CreateSubject(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - subject.DiscoverChanges(); - await subject.RaiseAfterSaveFailedAsyncTriggers(new Exception()); + subject.DiscoverChanges(); + await subject.RaiseAfterSaveFailedAsyncTriggers(new Exception()); - Assert.Single(context.TriggerStub.AfterSaveFailedAsyncInvocations); - } + Assert.Single(context.TriggerStub.AfterSaveFailedAsyncInvocations); + } - [Fact] - public void RaiseBeforeSaveTriggers_OnExceptionAndRecall_SkipsPreviousTriggers() - { - var firstTrigger = new TriggerStub { }; - var secondTrigger = new TriggerStub { }; - var lastTrigger = new TriggerStub { }; + [Fact] + public void RaiseBeforeSaveTriggers_OnExceptionAndRecall_SkipsPreviousTriggers() + { + var firstTrigger = new TriggerStub { }; + var secondTrigger = new TriggerStub { }; + var lastTrigger = new TriggerStub { }; - secondTrigger.BeforeSaveHandler = ctx => { - if (secondTrigger.BeforeSaveInvocations.Count == 0) - { - throw new Exception("oh oh!"); - } - }; - - var serviceProvider = new ServiceCollection() - .AddSingleton>(firstTrigger) - .AddSingleton>(secondTrigger) - .AddSingleton>(lastTrigger) - .AddTriggeredDbContext(options => { - options.UseInMemoryDatabase("Test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .BuildServiceProvider(); - - var scope = serviceProvider.CreateScope(); - var dbContext = scope.ServiceProvider.GetRequiredService(); - var subject = CreateSubject(dbContext); - - dbContext.TestModels.Add(new TestModel { Id = 1 }); - - try - { - subject.RaiseBeforeSaveTriggers(); - } - catch + secondTrigger.BeforeSaveHandler = ctx => { + if (secondTrigger.BeforeSaveInvocations.Count == 0) { - subject.RaiseBeforeSaveTriggers(); + throw new Exception("oh oh!"); } + }; + + var serviceProvider = new ServiceCollection() + .AddSingleton>(firstTrigger) + .AddSingleton>(secondTrigger) + .AddSingleton>(lastTrigger) + .AddTriggeredDbContext(options => { + options.UseInMemoryDatabase("Test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .BuildServiceProvider(); - Assert.Single(firstTrigger.BeforeSaveInvocations); - Assert.Single(secondTrigger.BeforeSaveInvocations); - Assert.Single(lastTrigger.BeforeSaveInvocations); - } + var scope = serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + var subject = CreateSubject(dbContext); + + dbContext.TestModels.Add(new TestModel { Id = 1 }); - [Fact] - public void RaiseAfterSaveTriggers_ModifiedEntity_HasAccessToUnmodifiedEntity() + try { - ITriggerContext _capturedTriggerContext = null; + subject.RaiseBeforeSaveTriggers(); + } + catch + { + subject.RaiseBeforeSaveTriggers(); + } - var trigger = new TriggerStub { - AfterSaveHandler = context => { - _capturedTriggerContext = context; - } - }; + Assert.Single(firstTrigger.BeforeSaveInvocations); + Assert.Single(secondTrigger.BeforeSaveInvocations); + Assert.Single(lastTrigger.BeforeSaveInvocations); + } + + [Fact] + public void RaiseAfterSaveTriggers_ModifiedEntity_HasAccessToUnmodifiedEntity() + { + ITriggerContext _capturedTriggerContext = null; + + var trigger = new TriggerStub { + AfterSaveHandler = context => { + _capturedTriggerContext = context; + } + }; - var serviceProvider = new ServiceCollection() - .AddSingleton>(trigger) - .AddTriggeredDbContext(options => { - options.UseInMemoryDatabase("Test"); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddSingleton>(trigger) + .AddTriggeredDbContext(options => { + options.UseInMemoryDatabase("Test"); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .BuildServiceProvider(); - var scope = serviceProvider.CreateScope(); - var dbContext = scope.ServiceProvider.GetRequiredService(); - var subject = CreateSubject(dbContext); - var testModel = new TestModel { Id = 1, Name = "test1" }; + var scope = serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + var subject = CreateSubject(dbContext); + var testModel = new TestModel { Id = 1, Name = "test1" }; - dbContext.TestModels.Add(testModel); - dbContext.SaveChanges(); + dbContext.TestModels.Add(testModel); + dbContext.SaveChanges(); - // act + // act - testModel.Name = "test2"; + testModel.Name = "test2"; - subject.DiscoverChanges(); - dbContext.SaveChanges(); - subject.RaiseAfterSaveTriggers(); + subject.DiscoverChanges(); + dbContext.SaveChanges(); + subject.RaiseAfterSaveTriggers(); - // assert + // assert - Assert.NotNull(_capturedTriggerContext); - Assert.Equal(ChangeType.Modified, _capturedTriggerContext.ChangeType); - Assert.Equal("test1", _capturedTriggerContext.UnmodifiedEntity.Name); - Assert.Equal("test2", _capturedTriggerContext.Entity.Name); - } + Assert.NotNull(_capturedTriggerContext); + Assert.Equal(ChangeType.Modified, _capturedTriggerContext.ChangeType); + Assert.Equal("test1", _capturedTriggerContext.UnmodifiedEntity.Name); + Assert.Equal("test2", _capturedTriggerContext.Entity.Name); + } - [Fact] - public void RaiseTriggers_DisabledConfiguration_Noop() - { - // arrange - using var context = new TestDbContext(); + [Fact] + public void RaiseTriggers_DisabledConfiguration_Noop() + { + // arrange + using var context = new TestDbContext(); - var triggerService = context.GetService(); - triggerService.Configuration = triggerService.Configuration with { - Disabled = true - }; + var triggerService = context.GetService(); + triggerService.Configuration = triggerService.Configuration with { + Disabled = true + }; - var subject = triggerService.CreateSession(context); + var subject = triggerService.CreateSession(context); - context.TestModels.Add(new TestModel { - Id = 1, - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = 1, + Name = "test1" + }); - // act - subject.RaiseBeforeSaveTriggers(); + // act + subject.RaiseBeforeSaveTriggers(); - // assert - Assert.Empty(context.TriggerStub.BeforeSaveInvocations); - } + // assert + Assert.Empty(context.TriggerStub.BeforeSaveInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs b/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs index bb360f5..c868127 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs +++ b/test/EntityFrameworkCore.Triggered.Tests/TriggeredDbContextFactoryTests.cs @@ -3,53 +3,52 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace EntityFrameworkCore.Triggered.Tests +namespace EntityFrameworkCore.Triggered.Tests; + +public class TriggeredDbContextFactoryTests { - public class TriggeredDbContextFactoryTests + public class TestModel + { + public Guid Id { get; set; } + public string Name { get; set; } + } + + class TestTrigger(TriggeredDbContextFactoryTests.TestDbContext testDbContext) : IBeforeSaveTrigger + { + readonly TestDbContext _testDbContext = testDbContext; + + public void BeforeSave(ITriggerContext context) => _testDbContext.TriggerRaised = true; + } + + class TestDbContext(DbContextOptions options) : DbContext(options) + { + public DbSet TestModels { get; set; } + + public bool TriggerRaised { get; set; } = false; + } + + [Fact] + public void DbContextFactory_RaisesTrigger_SharesDbContext() { - public class TestModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } - - class TestTrigger(TriggeredDbContextFactoryTests.TestDbContext testDbContext) : IBeforeSaveTrigger - { - readonly TestDbContext _testDbContext = testDbContext; - - public void BeforeSave(ITriggerContext context) => _testDbContext.TriggerRaised = true; - } - - class TestDbContext(DbContextOptions options) : DbContext(options) - { - public DbSet TestModels { get; set; } - - public bool TriggerRaised { get; set; } = false; - } - - [Fact] - public void DbContextFactory_RaisesTrigger_SharesDbContext() - { - using var serviceProvider = new ServiceCollection() - .AddTriggeredDbContextFactory(options => { - options.UseInMemoryDatabase(nameof(DbContextFactory_RaisesTrigger_SharesDbContext)); - options.UseTriggers(triggerOptions => { - triggerOptions.AddTrigger(); - }); - options.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - }) - .BuildServiceProvider(); - - using var serviceScope = serviceProvider.CreateScope(); - var dbContextFactory = serviceScope.ServiceProvider.GetService>(); - using var dbContext = dbContextFactory.CreateDbContext(); - - dbContext.TestModels.Add(new TestModel { }); - dbContext.SaveChanges(); - - Assert.True(dbContext.TriggerRaised); - } + using var serviceProvider = new ServiceCollection() + .AddTriggeredDbContextFactory(options => { + options.UseInMemoryDatabase(nameof(DbContextFactory_RaisesTrigger_SharesDbContext)); + options.UseTriggers(triggerOptions => { + triggerOptions.AddTrigger(); + }); + options.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + }) + .BuildServiceProvider(); + + using var serviceScope = serviceProvider.CreateScope(); + var dbContextFactory = serviceScope.ServiceProvider.GetService>(); + using var dbContext = dbContextFactory.CreateDbContext(); + + dbContext.TestModels.Add(new TestModel { }); + dbContext.SaveChanges(); + + Assert.True(dbContext.TriggerRaised); } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterCommitTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterCommitTriggerDescriptorTests.cs index 406a283..808615d 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterCommitTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterCommitTriggerDescriptorTests.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Transactions.Tests.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Tests.Internal; + +public class AfterCommitTriggerDescriptorTests { - public class AfterCommitTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new AfterCommitTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new AfterCommitTriggerDescriptor(entityType); - Assert.Equal(typeof(IAfterCommitTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IAfterCommitTrigger), subject.TriggerType); + } - [Fact] - public void Execute_ForwardsCall() - { - var entityType = typeof(string); - var triggerStub = new TriggerStub(); - var subject = new AfterCommitTriggerDescriptor(entityType); + [Fact] + public void Execute_ForwardsCall() + { + var entityType = typeof(string); + var triggerStub = new TriggerStub(); + var subject = new AfterCommitTriggerDescriptor(entityType); - subject.Invoke(triggerStub, new TriggerContextStub(), null); + subject.Invoke(triggerStub, new TriggerContextStub(), null); - Assert.Single(triggerStub.AfterCommitInvocations); - } + Assert.Single(triggerStub.AfterCommitInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterRollbackTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterRollbackTriggerDescriptorTests.cs index 8f508b5..1b46499 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterRollbackTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/AfterRollbackTriggerDescriptorTests.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Transactions.Tests.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Tests.Internal; + +public class AfterRollbackTriggerDescriptorTests { - public class AfterRollbackTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new AfterRollbackTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new AfterRollbackTriggerDescriptor(entityType); - Assert.Equal(typeof(IAfterRollbackTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IAfterRollbackTrigger), subject.TriggerType); + } - [Fact] - public void Execute_ForwardsCall() - { - var entityType = typeof(string); - var triggerStub = new TriggerStub(); - var subject = new AfterRollbackTriggerDescriptor(entityType); + [Fact] + public void Execute_ForwardsCall() + { + var entityType = typeof(string); + var triggerStub = new TriggerStub(); + var subject = new AfterRollbackTriggerDescriptor(entityType); - subject.Invoke(triggerStub, new TriggerContextStub(), null); + subject.Invoke(triggerStub, new TriggerContextStub(), null); - Assert.Single(triggerStub.AfterRollbackInvocations); - } + Assert.Single(triggerStub.AfterRollbackInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeCommitTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeCommitTriggerDescriptorTests.cs index 43fefcb..c85bc0c 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeCommitTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeCommitTriggerDescriptorTests.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Transactions.Tests.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Tests.Internal; + +public class BeforeCommitTriggerDescriptorTests { - public class BeforeCommitTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new BeforeCommitTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new BeforeCommitTriggerDescriptor(entityType); - Assert.Equal(typeof(IBeforeCommitTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IBeforeCommitTrigger), subject.TriggerType); + } - [Fact] - public void Execute_ForwardsCall() - { - var entityType = typeof(string); - var triggerStub = new TriggerStub(); - var subject = new BeforeCommitTriggerDescriptor(entityType); + [Fact] + public void Execute_ForwardsCall() + { + var entityType = typeof(string); + var triggerStub = new TriggerStub(); + var subject = new BeforeCommitTriggerDescriptor(entityType); - subject.Invoke(triggerStub, new TriggerContextStub(), null); + subject.Invoke(triggerStub, new TriggerContextStub(), null); - Assert.Single(triggerStub.BeforeCommitInvocations); - } + Assert.Single(triggerStub.BeforeCommitInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeRollbackTriggerDescriptorTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeRollbackTriggerDescriptorTests.cs index a2b9a0c..70118f4 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeRollbackTriggerDescriptorTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Internal/BeforeRollbackTriggerDescriptorTests.cs @@ -2,29 +2,28 @@ using EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; using Xunit; -namespace EntityFrameworkCore.Triggered.Transactions.Tests.Internal +namespace EntityFrameworkCore.Triggered.Transactions.Tests.Internal; + +public class BeforeRollbackTriggerDescriptorTests { - public class BeforeRollbackTriggerDescriptorTests + [Fact] + public void TriggerType_ReturnsConstructuredTriggerType() { - [Fact] - public void TriggerType_ReturnsConstructuredTriggerType() - { - var entityType = typeof(string); - var subject = new BeforeRollbackTriggerDescriptor(entityType); + var entityType = typeof(string); + var subject = new BeforeRollbackTriggerDescriptor(entityType); - Assert.Equal(typeof(IBeforeRollbackTrigger), subject.TriggerType); - } + Assert.Equal(typeof(IBeforeRollbackTrigger), subject.TriggerType); + } - [Fact] - public void Execute_ForwardsCall() - { - var entityType = typeof(string); - var triggerStub = new TriggerStub(); - var subject = new BeforeRollbackTriggerDescriptor(entityType); + [Fact] + public void Execute_ForwardsCall() + { + var entityType = typeof(string); + var triggerStub = new TriggerStub(); + var subject = new BeforeRollbackTriggerDescriptor(entityType); - subject.Invoke(triggerStub, new TriggerContextStub(), null); + subject.Invoke(triggerStub, new TriggerContextStub(), null); - Assert.Single(triggerStub.BeforeRollbackInvocations); - } + Assert.Single(triggerStub.BeforeRollbackInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerContextStub.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerContextStub.cs index 567881f..9a6b3b3 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerContextStub.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerContextStub.cs @@ -1,11 +1,10 @@ -namespace EntityFrameworkCore.Triggered.Transactions.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; + +public class TriggerContextStub : ITriggerContext + where TEntity : class { - public class TriggerContextStub : ITriggerContext - where TEntity : class - { - public ChangeType ChangeType { get; set; } - public TEntity Entity { get; set; } - public TEntity UnmodifiedEntity { get; set; } - public IDictionary Items { get; set; } - } + public ChangeType ChangeType { get; set; } + public TEntity Entity { get; set; } + public TEntity UnmodifiedEntity { get; set; } + public IDictionary Items { get; set; } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs index 425c509..2f36e5d 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/Stubs/TriggerStub.cs @@ -1,107 +1,106 @@ using EntityFrameworkCore.Triggered.Transactions.Lifecycles; -namespace EntityFrameworkCore.Triggered.Transactions.Tests.Stubs +namespace EntityFrameworkCore.Triggered.Transactions.Tests.Stubs; + +public class TriggerStub : + IBeforeCommitTrigger, + IBeforeCommitAsyncTrigger, + IAfterCommitTrigger, + IAfterCommitAsyncTrigger, + IBeforeRollbackTrigger, + IBeforeRollbackAsyncTrigger, + IAfterRollbackTrigger, + IAfterRollbackAsyncTrigger, + IBeforeCommitStartingTrigger, + IBeforeCommitStartingAsyncTrigger, + IBeforeCommitCompletedTrigger, + IBeforeCommitCompletedAsyncTrigger, + IAfterCommitStartingTrigger, + IAfterCommitStartingAsyncTrigger, + IAfterCommitCompletedTrigger, + IAfterCommitCompletedAsyncTrigger + + where TEntity : class { - public class TriggerStub : - IBeforeCommitTrigger, - IBeforeCommitAsyncTrigger, - IAfterCommitTrigger, - IAfterCommitAsyncTrigger, - IBeforeRollbackTrigger, - IBeforeRollbackAsyncTrigger, - IAfterRollbackTrigger, - IAfterRollbackAsyncTrigger, - IBeforeCommitStartingTrigger, - IBeforeCommitStartingAsyncTrigger, - IBeforeCommitCompletedTrigger, - IBeforeCommitCompletedAsyncTrigger, - IAfterCommitStartingTrigger, - IAfterCommitStartingAsyncTrigger, - IAfterCommitCompletedTrigger, - IAfterCommitCompletedAsyncTrigger - - where TEntity : class + public int BeforeCommitStartingInvocationsCount { get; set; } + public int BeforeCommitStartingAsyncInvocationsCount { get; set; } + public int BeforeCommitCompletedInvocationsCount { get; set; } + public int BeforeCommitCompletedAsyncInvocationsCount { get; set; } + public int AfterCommitStartingInvocationsCount { get; set; } + public int AfterCommitStartingAsyncInvocationsCount { get; set; } + public int AfterCommitCompletedInvocationsCount { get; set; } + public int AfterCommitCompletedAsyncInvocationsCount { get; set; } + + public ICollection> BeforeCommitInvocations { get; } = []; + public ICollection> BeforeCommitAsyncInvocations { get; } = []; + public ICollection> AfterCommitInvocations { get; } = []; + public ICollection> AfterCommitAsyncInvocations { get; } = []; + public ICollection> BeforeRollbackInvocations { get; } = []; + public ICollection> BeforeRollbackAsyncInvocations { get; } = []; + public ICollection> AfterRollbackInvocations { get; } = []; + public ICollection> AfterRollbackAsyncInvocations { get; } = []; + + public void BeforeCommitStarting() => BeforeCommitStartingInvocationsCount++; + + public Task BeforeCommitStartingAsync(CancellationToken cancellationToken) { - public int BeforeCommitStartingInvocationsCount { get; set; } - public int BeforeCommitStartingAsyncInvocationsCount { get; set; } - public int BeforeCommitCompletedInvocationsCount { get; set; } - public int BeforeCommitCompletedAsyncInvocationsCount { get; set; } - public int AfterCommitStartingInvocationsCount { get; set; } - public int AfterCommitStartingAsyncInvocationsCount { get; set; } - public int AfterCommitCompletedInvocationsCount { get; set; } - public int AfterCommitCompletedAsyncInvocationsCount { get; set; } - - public ICollection> BeforeCommitInvocations { get; } = []; - public ICollection> BeforeCommitAsyncInvocations { get; } = []; - public ICollection> AfterCommitInvocations { get; } = []; - public ICollection> AfterCommitAsyncInvocations { get; } = []; - public ICollection> BeforeRollbackInvocations { get; } = []; - public ICollection> BeforeRollbackAsyncInvocations { get; } = []; - public ICollection> AfterRollbackInvocations { get; } = []; - public ICollection> AfterRollbackAsyncInvocations { get; } = []; - - public void BeforeCommitStarting() => BeforeCommitStartingInvocationsCount++; - - public Task BeforeCommitStartingAsync(CancellationToken cancellationToken) - { - BeforeCommitStartingAsyncInvocationsCount++; - return Task.CompletedTask; - } - - public void BeforeCommitCompleted() => BeforeCommitCompletedInvocationsCount++; - - public Task BeforeCommitCompletedAsync(CancellationToken cancellationToken) - { - BeforeCommitCompletedAsyncInvocationsCount++; - return Task.CompletedTask; - } - - public void AfterCommitStarting() => AfterCommitStartingInvocationsCount++; - - public Task AfterCommitStartingAsync(CancellationToken cancellationToken) - { - AfterCommitStartingAsyncInvocationsCount++; - return Task.CompletedTask; - } - - public void AfterCommitCompleted() => AfterCommitCompletedInvocationsCount++; - - public Task AfterCommitCompletedAsync(CancellationToken cancellationToken) - { - AfterCommitCompletedAsyncInvocationsCount++; - return Task.CompletedTask; - } - - public void BeforeCommit(ITriggerContext context) => BeforeCommitInvocations.Add(context); - - public Task BeforeCommitAsync(ITriggerContext context, CancellationToken cancellationToken) - { - BeforeCommitAsyncInvocations.Add(context); - return Task.CompletedTask; - } - - public void AfterCommit(ITriggerContext context) => AfterCommitInvocations.Add(context); - - public Task AfterCommitAsync(ITriggerContext context, CancellationToken cancellationToken) - { - AfterCommitAsyncInvocations.Add(context); - return Task.CompletedTask; - } - - public void BeforeRollback(ITriggerContext context) => BeforeRollbackInvocations.Add(context); - - public Task BeforeRollbackAsync(ITriggerContext context, CancellationToken cancellationToken) - { - BeforeRollbackAsyncInvocations.Add(context); - return Task.CompletedTask; - } - - public void AfterRollback(ITriggerContext context) => AfterRollbackInvocations.Add(context); - - public Task AfterRollbackAsync(ITriggerContext context, CancellationToken cancellationToken) - { - AfterRollbackAsyncInvocations.Add(context); - return Task.CompletedTask; - } + BeforeCommitStartingAsyncInvocationsCount++; + return Task.CompletedTask; + } + + public void BeforeCommitCompleted() => BeforeCommitCompletedInvocationsCount++; + + public Task BeforeCommitCompletedAsync(CancellationToken cancellationToken) + { + BeforeCommitCompletedAsyncInvocationsCount++; + return Task.CompletedTask; + } + + public void AfterCommitStarting() => AfterCommitStartingInvocationsCount++; + + public Task AfterCommitStartingAsync(CancellationToken cancellationToken) + { + AfterCommitStartingAsyncInvocationsCount++; + return Task.CompletedTask; + } + + public void AfterCommitCompleted() => AfterCommitCompletedInvocationsCount++; + + public Task AfterCommitCompletedAsync(CancellationToken cancellationToken) + { + AfterCommitCompletedAsyncInvocationsCount++; + return Task.CompletedTask; + } + + public void BeforeCommit(ITriggerContext context) => BeforeCommitInvocations.Add(context); + + public Task BeforeCommitAsync(ITriggerContext context, CancellationToken cancellationToken) + { + BeforeCommitAsyncInvocations.Add(context); + return Task.CompletedTask; + } + + public void AfterCommit(ITriggerContext context) => AfterCommitInvocations.Add(context); + + public Task AfterCommitAsync(ITriggerContext context, CancellationToken cancellationToken) + { + AfterCommitAsyncInvocations.Add(context); + return Task.CompletedTask; + } + + public void BeforeRollback(ITriggerContext context) => BeforeRollbackInvocations.Add(context); + + public Task BeforeRollbackAsync(ITriggerContext context, CancellationToken cancellationToken) + { + BeforeRollbackAsyncInvocations.Add(context); + return Task.CompletedTask; + } + + public void AfterRollback(ITriggerContext context) => AfterRollbackInvocations.Add(context); + + public Task AfterRollbackAsync(ITriggerContext context, CancellationToken cancellationToken) + { + AfterRollbackAsyncInvocations.Add(context); + return Task.CompletedTask; } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs index 76461f9..1e712e4 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredDbContextTests.cs @@ -4,74 +4,73 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; -namespace EntityFrameworkCore.Triggered.Transactions.Tests +namespace EntityFrameworkCore.Triggered.Transactions.Tests; + +public class TriggeredDbContextTests { - public class TriggeredDbContextTests + class TestModel { - class TestModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } + public Guid Id { get; set; } + public string Name { get; set; } + } - class TestDbContext : DbContext - { - public TriggerStub TriggerStub { get; } = new TriggerStub(); + class TestDbContext : DbContext + { + public TriggerStub TriggerStub { get; } = new TriggerStub(); - public DbSet TestModels { get; set; } + public DbSet TestModels { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - base.OnConfiguring(optionsBuilder); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); - optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.UseTriggers(triggerOptions => { - triggerOptions - .UseTransactionTriggers() - .AddTrigger(TriggerStub); - }); - } + optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.UseTriggers(triggerOptions => { + triggerOptions + .UseTransactionTriggers() + .AddTrigger(TriggerStub); + }); } + } - [Fact] - public void RaiseBeforeCommitTriggers_DiscoveredChangesFromTriggeredDbContext_CallsTriggers() - { - var dbContext = new TestDbContext(); - using var subject = dbContext.CreateTriggerSession(); + [Fact] + public void RaiseBeforeCommitTriggers_DiscoveredChangesFromTriggeredDbContext_CallsTriggers() + { + var dbContext = new TestDbContext(); + using var subject = dbContext.CreateTriggerSession(); - dbContext.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + dbContext.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - dbContext.SaveChanges(); + dbContext.SaveChanges(); - subject.RaiseBeforeCommitTriggers(); + subject.RaiseBeforeCommitTriggers(); - Assert.Single(dbContext.TriggerStub.BeforeCommitInvocations); - } + Assert.Single(dbContext.TriggerStub.BeforeCommitInvocations); + } - [Fact] - public void RaiseAfterCommitTriggers_DiscoveredChangesFromTriggeredDbContext_CallsTriggers() - { - var dbContext = new TestDbContext(); - using var subject = dbContext.CreateTriggerSession(); + [Fact] + public void RaiseAfterCommitTriggers_DiscoveredChangesFromTriggeredDbContext_CallsTriggers() + { + var dbContext = new TestDbContext(); + using var subject = dbContext.CreateTriggerSession(); - dbContext.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + dbContext.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - dbContext.SaveChanges(); + dbContext.SaveChanges(); - subject.RaiseAfterCommitTriggers(); + subject.RaiseAfterCommitTriggers(); - Assert.Single(dbContext.TriggerStub.AfterCommitInvocations); - } + Assert.Single(dbContext.TriggerStub.AfterCommitInvocations); } } diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs index 62dd74f..7f3f670 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/TriggeredSessionExtensionsTests.cs @@ -4,360 +4,359 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Xunit; -namespace EntityFrameworkCore.Triggered.Transactions.Tests +namespace EntityFrameworkCore.Triggered.Transactions.Tests; + +public class TriggeredSessionExtensionsTests { - public class TriggeredSessionExtensionsTests + class TestModel { - class TestModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } + public Guid Id { get; set; } + public string Name { get; set; } + } - class TestDbContext : DbContext + class TestDbContext : DbContext + { + public TriggerStub TriggerStub { get; } = new TriggerStub(); + + public DbSet TestModels { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - public TriggerStub TriggerStub { get; } = new TriggerStub(); - - public DbSet TestModels { get; set; } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - base.OnConfiguring(optionsBuilder); - - optionsBuilder.ConfigureWarnings(warningOptions => { - warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); - }); - optionsBuilder.UseInMemoryDatabase("test"); - optionsBuilder.UseTriggers(triggerOptions => { - triggerOptions - .UseTransactionTriggers() - .AddTrigger(TriggerStub); - }); - } + base.OnConfiguring(optionsBuilder); + + optionsBuilder.ConfigureWarnings(warningOptions => { + warningOptions.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning); + }); + optionsBuilder.UseInMemoryDatabase("test"); + optionsBuilder.UseTriggers(triggerOptions => { + triggerOptions + .UseTransactionTriggers() + .AddTrigger(TriggerStub); + }); } + } - protected static ITriggerSession CreateSession(DbContext context) - => context.Database.GetService().CreateSession(context); + protected static ITriggerSession CreateSession(DbContext context) + => context.Database.GetService().CreateSession(context); - [Fact] - public void RaiseBeforeCommitTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseBeforeCommitTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.DiscoverChanges(); - session.RaiseBeforeCommitTriggers(); + session.DiscoverChanges(); + session.RaiseBeforeCommitTriggers(); - Assert.Empty(context.TriggerStub.BeforeCommitInvocations); - } + Assert.Empty(context.TriggerStub.BeforeCommitInvocations); + } - [Fact] - public async Task RaiseBeforeCommitAsyncTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseBeforeCommitAsyncTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.DiscoverChanges(); - await session.RaiseBeforeCommitAsyncTriggers(); + session.DiscoverChanges(); + await session.RaiseBeforeCommitAsyncTriggers(); - Assert.Empty(context.TriggerStub.BeforeCommitAsyncInvocations); - } + Assert.Empty(context.TriggerStub.BeforeCommitAsyncInvocations); + } - [Fact] - public void RaiseBeforeCommitTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseBeforeCommitTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - context.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - session.DiscoverChanges(); - session.RaiseBeforeCommitTriggers(); + session.DiscoverChanges(); + session.RaiseBeforeCommitTriggers(); - Assert.Single(context.TriggerStub.BeforeCommitInvocations); - } + Assert.Single(context.TriggerStub.BeforeCommitInvocations); + } - [Fact] - public async Task RaiseBeforeCommitAsyncTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseBeforeCommitAsyncTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - context.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - session.DiscoverChanges(); - await session.RaiseBeforeCommitAsyncTriggers(); + session.DiscoverChanges(); + await session.RaiseBeforeCommitAsyncTriggers(); - Assert.Single(context.TriggerStub.BeforeCommitAsyncInvocations); - } + Assert.Single(context.TriggerStub.BeforeCommitAsyncInvocations); + } - [Fact] - public void RaiseAfterCommitTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseAfterCommitTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.DiscoverChanges(); - session.RaiseAfterCommitTriggers(); + session.DiscoverChanges(); + session.RaiseAfterCommitTriggers(); - Assert.Empty(context.TriggerStub.AfterCommitInvocations); - } + Assert.Empty(context.TriggerStub.AfterCommitInvocations); + } - [Fact] - public async Task RaiseAfterCommitAsyncTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseAfterCommitAsyncTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.DiscoverChanges(); - await session.RaiseAfterCommitAsyncTriggers(); + session.DiscoverChanges(); + await session.RaiseAfterCommitAsyncTriggers(); - Assert.Empty(context.TriggerStub.AfterCommitAsyncInvocations); - } + Assert.Empty(context.TriggerStub.AfterCommitAsyncInvocations); + } - [Fact] - public void RaiseAfterCommitTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseAfterCommitTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - context.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - session.DiscoverChanges(); - session.RaiseAfterCommitTriggers(); + session.DiscoverChanges(); + session.RaiseAfterCommitTriggers(); - Assert.Single(context.TriggerStub.AfterCommitInvocations); - } + Assert.Single(context.TriggerStub.AfterCommitInvocations); + } - [Fact] - public async Task RaiseAfterCommitAsyncTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseAfterCommitAsyncTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - context.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - session.DiscoverChanges(); - await session.RaiseAfterCommitAsyncTriggers(); + session.DiscoverChanges(); + await session.RaiseAfterCommitAsyncTriggers(); - Assert.Single(context.TriggerStub.AfterCommitAsyncInvocations); - } + Assert.Single(context.TriggerStub.AfterCommitAsyncInvocations); + } - [Fact] - public void RaiseBeforeRollbackTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseBeforeRollbackTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.DiscoverChanges(); - session.RaiseBeforeRollbackTriggers(); + session.DiscoverChanges(); + session.RaiseBeforeRollbackTriggers(); - Assert.Empty(context.TriggerStub.BeforeRollbackInvocations); - } + Assert.Empty(context.TriggerStub.BeforeRollbackInvocations); + } - [Fact] - public async Task RaiseBeforeRollbackAsyncTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseBeforeRollbackAsyncTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.DiscoverChanges(); - await session.RaiseBeforeRollbackAsyncTriggers(); + session.DiscoverChanges(); + await session.RaiseBeforeRollbackAsyncTriggers(); - Assert.Empty(context.TriggerStub.BeforeRollbackAsyncInvocations); - } + Assert.Empty(context.TriggerStub.BeforeRollbackAsyncInvocations); + } - [Fact] - public void RaiseBeforeRollbackTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseBeforeRollbackTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - context.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - session.DiscoverChanges(); - session.RaiseBeforeRollbackTriggers(); + session.DiscoverChanges(); + session.RaiseBeforeRollbackTriggers(); - Assert.Single(context.TriggerStub.BeforeRollbackInvocations); - } + Assert.Single(context.TriggerStub.BeforeRollbackInvocations); + } - [Fact] - public async Task RaiseBeforeRollbackAsyncTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseBeforeRollbackAsyncTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - context.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - session.DiscoverChanges(); - await session.RaiseBeforeRollbackAsyncTriggers(); + session.DiscoverChanges(); + await session.RaiseBeforeRollbackAsyncTriggers(); - Assert.Single(context.TriggerStub.BeforeRollbackAsyncInvocations); - } + Assert.Single(context.TriggerStub.BeforeRollbackAsyncInvocations); + } - [Fact] - public void RaiseAfterRollbackTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseAfterRollbackTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.DiscoverChanges(); - session.RaiseAfterRollbackTriggers(); + session.DiscoverChanges(); + session.RaiseAfterRollbackTriggers(); - Assert.Empty(context.TriggerStub.AfterRollbackInvocations); - } + Assert.Empty(context.TriggerStub.AfterRollbackInvocations); + } - [Fact] - public async Task RaiseAfterRollbackAsyncTriggers_RaisesNothingOnNoChanges() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseAfterRollbackAsyncTriggers_RaisesNothingOnNoChanges() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.DiscoverChanges(); - await session.RaiseAfterRollbackAsyncTriggers(); + session.DiscoverChanges(); + await session.RaiseAfterRollbackAsyncTriggers(); - Assert.Empty(context.TriggerStub.AfterRollbackAsyncInvocations); - } + Assert.Empty(context.TriggerStub.AfterRollbackAsyncInvocations); + } - [Fact] - public void RaiseAfterRollbackTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseAfterRollbackTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - context.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - session.DiscoverChanges(); - session.RaiseAfterRollbackTriggers(); + session.DiscoverChanges(); + session.RaiseAfterRollbackTriggers(); - Assert.Single(context.TriggerStub.AfterRollbackInvocations); - } + Assert.Single(context.TriggerStub.AfterRollbackInvocations); + } - [Fact] - public async Task RaiseAfterRollbackAsyncTriggers_RaisesOnceOnSimpleAddition() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseAfterRollbackAsyncTriggers_RaisesOnceOnSimpleAddition() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - context.TestModels.Add(new TestModel { - Id = Guid.NewGuid(), - Name = "test1" - }); + context.TestModels.Add(new TestModel { + Id = Guid.NewGuid(), + Name = "test1" + }); - session.DiscoverChanges(); - await session.RaiseAfterRollbackAsyncTriggers(); + session.DiscoverChanges(); + await session.RaiseAfterRollbackAsyncTriggers(); - Assert.Single(context.TriggerStub.AfterRollbackAsyncInvocations); - } + Assert.Single(context.TriggerStub.AfterRollbackAsyncInvocations); + } - [Fact] - public void RaiseBeforeCommitStartingTriggers_CallsTriggers() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseBeforeCommitStartingTriggers_CallsTriggers() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.RaiseBeforeCommitStartingTriggers(); + session.RaiseBeforeCommitStartingTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeCommitStartingInvocationsCount); - } + Assert.Equal(1, context.TriggerStub.BeforeCommitStartingInvocationsCount); + } - [Fact] - public async Task RaiseBeforeCommitStartingAsyncTriggers_CallsTriggers() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseBeforeCommitStartingAsyncTriggers_CallsTriggers() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - await session.RaiseBeforeCommitStartingAsyncTriggers(); + await session.RaiseBeforeCommitStartingAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeCommitStartingAsyncInvocationsCount); - } + Assert.Equal(1, context.TriggerStub.BeforeCommitStartingAsyncInvocationsCount); + } - [Fact] - public void RaiseBeforeCommitCompletedTriggers_CallsTriggers() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseBeforeCommitCompletedTriggers_CallsTriggers() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.RaiseBeforeCommitCompletedTriggers(); + session.RaiseBeforeCommitCompletedTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeCommitCompletedInvocationsCount); - } + Assert.Equal(1, context.TriggerStub.BeforeCommitCompletedInvocationsCount); + } - [Fact] - public async Task RaiseBeforeCommitCompletedAsyncTriggers_CallsTriggers() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseBeforeCommitCompletedAsyncTriggers_CallsTriggers() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - await session.RaiseBeforeCommitCompletedAsyncTriggers(); + await session.RaiseBeforeCommitCompletedAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.BeforeCommitCompletedAsyncInvocationsCount); - } + Assert.Equal(1, context.TriggerStub.BeforeCommitCompletedAsyncInvocationsCount); + } - [Fact] - public void RaiseAfterCommitStartingTriggers_CallsTriggers() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseAfterCommitStartingTriggers_CallsTriggers() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.RaiseAfterCommitStartingTriggers(); + session.RaiseAfterCommitStartingTriggers(); - Assert.Equal(1, context.TriggerStub.AfterCommitStartingInvocationsCount); - } + Assert.Equal(1, context.TriggerStub.AfterCommitStartingInvocationsCount); + } - [Fact] - public async Task RaiseAfterCommitStartingAsyncTriggers_CallsTriggers() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseAfterCommitStartingAsyncTriggers_CallsTriggers() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - await session.RaiseAfterCommitStartingAsyncTriggers(); + await session.RaiseAfterCommitStartingAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.AfterCommitStartingAsyncInvocationsCount); - } + Assert.Equal(1, context.TriggerStub.AfterCommitStartingAsyncInvocationsCount); + } - [Fact] - public void RaiseAfterCommitCompletedTrigger_CallsTriggers() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public void RaiseAfterCommitCompletedTrigger_CallsTriggers() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - session.RaiseAfterCommitCompletedTriggers(); + session.RaiseAfterCommitCompletedTriggers(); - Assert.Equal(1, context.TriggerStub.AfterCommitCompletedInvocationsCount); - } + Assert.Equal(1, context.TriggerStub.AfterCommitCompletedInvocationsCount); + } - [Fact] - public async Task RaiseAfterCommitCompletedAsyncTrigger_CallsTriggers() - { - using var context = new TestDbContext(); - var session = CreateSession(context); + [Fact] + public async Task RaiseAfterCommitCompletedAsyncTrigger_CallsTriggers() + { + using var context = new TestDbContext(); + var session = CreateSession(context); - await session.RaiseAfterCommitCompletedAsyncTriggers(); + await session.RaiseAfterCommitCompletedAsyncTriggers(); - Assert.Equal(1, context.TriggerStub.AfterCommitCompletedAsyncInvocationsCount); - } + Assert.Equal(1, context.TriggerStub.AfterCommitCompletedAsyncInvocationsCount); } } From 41f27de150a894ffe1178057af7c39edfdc958d6 Mon Sep 17 00:00:00 2001 From: Koen Date: Sun, 11 Feb 2024 18:37:03 +0000 Subject: [PATCH 10/16] Removed unused internal attribute --- .../Internal/IsExternalInit.cs | 22 ------------------- 1 file changed, 22 deletions(-) delete mode 100644 src/EntityFrameworkCore.Triggered.Abstractions/Internal/IsExternalInit.cs diff --git a/src/EntityFrameworkCore.Triggered.Abstractions/Internal/IsExternalInit.cs b/src/EntityFrameworkCore.Triggered.Abstractions/Internal/IsExternalInit.cs deleted file mode 100644 index 5fe34e5..0000000 --- a/src/EntityFrameworkCore.Triggered.Abstractions/Internal/IsExternalInit.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#if NETSTANDARD2_0 || NETSTANDARD2_1 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 || NETCOREAPP3_0 || NETCOREAPP3_1 || NET45 || NET451 || NET452 || NET6 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48 - -using System.ComponentModel; - -// ReSharper disable once CheckNamespace -namespace System.Runtime.CompilerServices -{ - /// - /// Reserved to be used by the compiler for tracking metadata. - /// This class should not be used by developers in source code. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - internal static class IsExternalInit - { - } -} - -#endif \ No newline at end of file From af0284d02c0763791bd7c9f28487b560299eacea Mon Sep 17 00:00:00 2001 From: Koen Date: Tue, 5 Nov 2024 01:51:21 +0000 Subject: [PATCH 11/16] Cleaned up csproj --- .../EntityFrameworkCore.Triggered.Benchmarks.csproj | 1 - samples/1 - HelloWorld/1 - HelloWorld.csproj | 2 -- samples/2 - PrimarySchool/2 - PrimarySchool.csproj | 5 +---- .../3 - StudentManagerAspNetCore.csproj | 2 -- samples/4 - BlazorTests/4 - BlazorTests.csproj | 5 +---- src/Directory.Build.props | 4 ---- .../EntityFrameworkCore.Triggered.csproj | 5 +---- .../EntityFrameworkCore.Triggered.Extensions.Tests.csproj | 6 +----- .../EntityFrameworkCore.Triggered.IntegrationTests.csproj | 6 +----- .../EntityFrameworkCore.Triggered.Tests.csproj | 6 +----- .../EntityFrameworkCore.Triggered.Transactions.Tests.csproj | 4 +--- 11 files changed, 7 insertions(+), 39 deletions(-) diff --git a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj index 6722f17..1ff119b 100644 --- a/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj +++ b/benchmarks/EntityFrameworkCore.Triggered.Benchmarks/EntityFrameworkCore.Triggered.Benchmarks.csproj @@ -18,5 +18,4 @@ - \ No newline at end of file diff --git a/samples/1 - HelloWorld/1 - HelloWorld.csproj b/samples/1 - HelloWorld/1 - HelloWorld.csproj index dafcafd..c743d12 100644 --- a/samples/1 - HelloWorld/1 - HelloWorld.csproj +++ b/samples/1 - HelloWorld/1 - HelloWorld.csproj @@ -1,11 +1,9 @@  - Exe HelloWorld disable - diff --git a/samples/2 - PrimarySchool/2 - PrimarySchool.csproj b/samples/2 - PrimarySchool/2 - PrimarySchool.csproj index 6a8d09a..e1d88d3 100644 --- a/samples/2 - PrimarySchool/2 - PrimarySchool.csproj +++ b/samples/2 - PrimarySchool/2 - PrimarySchool.csproj @@ -1,11 +1,9 @@  - Exe PrimarySchool disable - @@ -13,5 +11,4 @@ - - + \ No newline at end of file diff --git a/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj b/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj index d2adb4e..e69e7e8 100644 --- a/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj +++ b/samples/3 - StudentManagerAspNetCore/3 - StudentManagerAspNetCore.csproj @@ -1,10 +1,8 @@  - StudentManager disable - diff --git a/samples/4 - BlazorTests/4 - BlazorTests.csproj b/samples/4 - BlazorTests/4 - BlazorTests.csproj index f5327f9..cc542ce 100644 --- a/samples/4 - BlazorTests/4 - BlazorTests.csproj +++ b/samples/4 - BlazorTests/4 - BlazorTests.csproj @@ -1,10 +1,8 @@  - BlazorTests disable - @@ -12,5 +10,4 @@ - - + \ No newline at end of file diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 71dd1fc..134a121 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,6 +1,5 @@ - true true @@ -13,13 +12,10 @@ True $(NoWarn);CS1591;CS1573 - true - - \ No newline at end of file diff --git a/src/EntityFrameworkCore.Triggered/EntityFrameworkCore.Triggered.csproj b/src/EntityFrameworkCore.Triggered/EntityFrameworkCore.Triggered.csproj index 909d546..b7ddac8 100644 --- a/src/EntityFrameworkCore.Triggered/EntityFrameworkCore.Triggered.csproj +++ b/src/EntityFrameworkCore.Triggered/EntityFrameworkCore.Triggered.csproj @@ -1,11 +1,8 @@  - - - - + \ No newline at end of file diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj b/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj index 22c674e..1657e47 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/EntityFrameworkCore.Triggered.Extensions.Tests.csproj @@ -1,9 +1,7 @@  - disable - all @@ -18,9 +16,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - - - + \ No newline at end of file diff --git a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj index 832ac40..b10cec0 100644 --- a/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj +++ b/test/EntityFrameworkCore.Triggered.IntegrationTests/EntityFrameworkCore.Triggered.IntegrationTests.csproj @@ -1,9 +1,7 @@ - disable - all @@ -18,9 +16,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - - - + \ No newline at end of file diff --git a/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj b/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj index 4234e8b..9f80bd6 100644 --- a/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj +++ b/test/EntityFrameworkCore.Triggered.Tests/EntityFrameworkCore.Triggered.Tests.csproj @@ -1,9 +1,7 @@  - disable - all @@ -19,9 +17,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - - - + \ No newline at end of file diff --git a/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj b/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj index 6d4d2e8..1979659 100644 --- a/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj +++ b/test/EntityFrameworkCore.Triggered.Transactions.Tests/EntityFrameworkCore.Triggered.Transactions.Tests.csproj @@ -1,5 +1,4 @@ - disable @@ -22,5 +21,4 @@ - - + \ No newline at end of file From 79f77cf60a5228a17f1f31fd24cffec403562aa3 Mon Sep 17 00:00:00 2001 From: Koen Date: Tue, 5 Nov 2024 01:54:25 +0000 Subject: [PATCH 12/16] Updated EFCore database providers --- Directory.Packages.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index e7da195..7d38912 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,8 +5,8 @@ - - + + From 7b3c97c9bb70df36304f7f70cf64abfdf9dbd2a4 Mon Sep 17 00:00:00 2001 From: Koen Date: Tue, 5 Nov 2024 02:04:53 +0000 Subject: [PATCH 13/16] Updated test dependencies --- Directory.Packages.props | 8 ++++---- .../ServiceCollectionExtensionsTests.cs | 2 +- .../TriggerContextOptionsBuilderExtensionsTests.cs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 7d38912..9bfba34 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -8,10 +8,10 @@ - + - - - + + + \ No newline at end of file diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs index 61622a6..b379855 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/ServiceCollectionExtensionsTests.cs @@ -134,7 +134,7 @@ public void AddAssemblyTriggers_AbstractTrigger_GetsIgnored() .AddAssemblyTriggers(); // Ensure that we did not register the AbstractTrigger - Assert.Empty(serviceCollection.Where(x => x.ImplementationType == typeof(AbstractTrigger))); + Assert.DoesNotContain(serviceCollection, x => x.ImplementationType == typeof(AbstractTrigger)); } [Theory] diff --git a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs index aad4a0b..65e91f3 100644 --- a/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs +++ b/test/EntityFrameworkCore.Triggered.Extensions.Tests/TriggerContextOptionsBuilderExtensionsTests.cs @@ -19,6 +19,6 @@ public void AddAssemblyTriggers_AbstractTrigger_GetsIgnored() var triggerOptionExtension = context.Options.Extensions.OfType().Single(); // Ensure that we did not register the AbstractTrigger - Assert.Empty(triggerOptionExtension.Triggers.Where(x => ReferenceEquals(x.typeOrInstance, typeof(AbstractTrigger)))); + Assert.DoesNotContain(triggerOptionExtension.Triggers, x => ReferenceEquals(x.typeOrInstance, typeof(AbstractTrigger))); } } From 4064d5431d14149a2dc392e20460b2ab19bdeef3 Mon Sep 17 00:00:00 2001 From: Koen Date: Tue, 5 Nov 2024 02:05:51 +0000 Subject: [PATCH 14/16] Suppress warning --- Directory.Packages.props | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Directory.Packages.props b/Directory.Packages.props index 9bfba34..6450774 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,6 +1,8 @@ true + false + $(NoWarn);NU1903 From 28bf2b45317a55dc222b64a85c4fd6410a800b21 Mon Sep 17 00:00:00 2001 From: Koen Date: Tue, 5 Nov 2024 02:06:18 +0000 Subject: [PATCH 15/16] No need for the worker SDK --- samples/2 - PrimarySchool/2 - PrimarySchool.csproj | 2 +- samples/2 - PrimarySchool/Program.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/samples/2 - PrimarySchool/2 - PrimarySchool.csproj b/samples/2 - PrimarySchool/2 - PrimarySchool.csproj index e1d88d3..0b915c3 100644 --- a/samples/2 - PrimarySchool/2 - PrimarySchool.csproj +++ b/samples/2 - PrimarySchool/2 - PrimarySchool.csproj @@ -1,4 +1,4 @@ - + Exe PrimarySchool diff --git a/samples/2 - PrimarySchool/Program.cs b/samples/2 - PrimarySchool/Program.cs index 727d9f6..7dd3ab4 100644 --- a/samples/2 - PrimarySchool/Program.cs +++ b/samples/2 - PrimarySchool/Program.cs @@ -1,4 +1,5 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using PrimarySchool; using PrimarySchool.Triggers; From 52b8ee64c33fd682ca0820625c613949a03b8d7c Mon Sep 17 00:00:00 2001 From: Koen Date: Tue, 5 Nov 2024 02:07:43 +0000 Subject: [PATCH 16/16] Drop explicit sourcelink dependency --- Directory.Packages.props | 1 - src/Directory.Build.props | 3 --- 2 files changed, 4 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 6450774..224a642 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,7 +9,6 @@ - diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 134a121..5257dd3 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -15,7 +15,4 @@ true - - - \ No newline at end of file