Repository: alexandre-spieser/mongodb-generic-repository Branch: master Commit: 0c20dfca3894 Files: 254 Total size: 2.6 MB Directory structure: gitextract_61u1jiz3/ ├── .gitignore ├── CoreIntegrationTests/ │ ├── App.config │ ├── CRUDObjectIdTests.cs │ ├── CRUDPartitionedCollectionNameAttributeTests.cs │ ├── CRUDPartitionedTests.cs │ ├── CRUDTKeyPartitionedCollectionNameAttributeTests.cs │ ├── CRUDTKeyPartitionedTests.cs │ ├── CRUDTKeyTests.cs │ ├── CRUDTests.cs │ ├── CoreIntegrationTests.csproj │ ├── IdentityUserTests.cs │ └── Infrastructure/ │ ├── BaseMongoDbRepositoryTests.cs │ ├── GlobalVariables.cs │ ├── ITestRepository.cs │ ├── MongoDbConfig.cs │ ├── MongoDbDocumentTestBase.Main.cs │ ├── MongoDbDocumentTestBase.Update.cs │ ├── MongoDbTKeyDocumentTestBase.Main.cs │ ├── MongoDbTKeyDocumentTestBase.Update.cs │ ├── MongoDbTestFixture.cs │ ├── RandomExtensions.cs │ ├── TestClasses.cs │ └── TestRepository.cs ├── CoreUnitTests/ │ ├── .editorconfig │ ├── BaseMongoRepositoryTests/ │ │ ├── AddTests/ │ │ │ ├── AddManyAsyncTests.cs │ │ │ ├── AddManyTests.cs │ │ │ ├── AddOneAsyncTests.cs │ │ │ └── AddOneTests.cs │ │ ├── DeleteTests/ │ │ │ ├── DeleteManyAsyncTests.cs │ │ │ ├── DeleteManyTests.cs │ │ │ ├── DeleteOneAsyncTests.cs │ │ │ └── DeleteOneTests.cs │ │ ├── IndexTests/ │ │ │ ├── BaseIndexTests.cs │ │ │ ├── CreateAscendingIndexAsyncTests.cs │ │ │ ├── CreateCombinedTextIndexAsyncTests.cs │ │ │ ├── CreateDescendingIndexAsyncTests.cs │ │ │ ├── CreateHashedIndexAsyncTests.cs │ │ │ ├── CreateTextIndexAsyncTests.cs │ │ │ ├── DropIndexAsyncTests.cs │ │ │ └── GetIndexNamesAsyncTests.cs │ │ └── UpdateTests/ │ │ ├── UpdateManyAsyncTests.cs │ │ ├── UpdateManyTests.cs │ │ ├── UpdateOneAsyncTests.cs │ │ └── UpdateOneTests.cs │ ├── CoreUnitTests.csproj │ ├── DataAccessTests/ │ │ ├── MongoDbCreatorTests/ │ │ │ ├── AddManyAsyncTests.cs │ │ │ ├── AddManyTests.cs │ │ │ ├── AddOneAsyncTests.cs │ │ │ └── AddOneTests.cs │ │ ├── MongoDbEraserTests/ │ │ │ ├── DeleteManyAsyncTests.cs │ │ │ ├── DeleteManyTests.cs │ │ │ ├── DeleteOneAsyncTests.cs │ │ │ └── DeleteOneTests.cs │ │ ├── MongoDbIndexHandlerTests/ │ │ │ ├── BaseIndexTests.cs │ │ │ ├── CreateAscendingIndexAsyncTests.cs │ │ │ ├── CreateCombinedTextIndexAsyncTests.cs │ │ │ ├── CreateDescendingIndexAsyncTests.cs │ │ │ ├── CreateHashedIndexAsyncTests.cs │ │ │ ├── CreateTextIndexAsyncTests.cs │ │ │ ├── DropIndexAsyncTests.cs │ │ │ └── GetIndexNamesAsyncTests.cs │ │ ├── MongoDbReaderTests/ │ │ │ ├── AnyAsyncTests.cs │ │ │ ├── AnyTests.cs │ │ │ ├── BaseReaderTests.cs │ │ │ ├── CountAsyncTests.cs │ │ │ ├── CountTests.cs │ │ │ ├── GetAllAsyncTests.cs │ │ │ ├── GetAllTests.cs │ │ │ ├── GetByIdAsyncTests.cs │ │ │ ├── GetByIdTests.cs │ │ │ ├── GetByMaxAsyncTests.cs │ │ │ ├── GetByMaxTests.cs │ │ │ ├── GetByMinAsyncTests.cs │ │ │ ├── GetByMinTests.cs │ │ │ ├── GetMaxValueAsyncTests .cs │ │ │ ├── GetMaxValueTests .cs │ │ │ ├── GetMinValueAsyncTests .cs │ │ │ ├── GetMinValueTests .cs │ │ │ ├── GetOneAsyncTests.cs │ │ │ ├── GetOneTests.cs │ │ │ ├── ProjectManyAsyncTests.cs │ │ │ ├── ProjectManyTests.cs │ │ │ ├── ProjectOneAsyncTests.cs │ │ │ └── ProjectOneTests.cs │ │ └── MongoDbUpdaterTests/ │ │ ├── UpdateManyAsyncTests.cs │ │ ├── UpdateManyTests.cs │ │ ├── UpdateOneAsyncTests.cs │ │ └── UpdateOneTests.cs │ ├── Infrastructure/ │ │ ├── FilterDefinitionExtensions.cs │ │ ├── GenericTestContext.cs │ │ ├── IndexExtensions.cs │ │ ├── Model/ │ │ │ ├── Child.cs │ │ │ ├── Nested.cs │ │ │ ├── PartitionedTestDocument.cs │ │ │ ├── TestDocument.cs │ │ │ ├── TestDocumentWithKey.cs │ │ │ └── TestProjection.cs │ │ ├── TestKeyedMongoRepository.cs │ │ ├── TestKeyedMongoRepositoryContext.cs │ │ ├── TestKeyedReadOnlyMongoRepository.cs │ │ ├── TestKeyedReadOnlyMongoRepositoryContext.cs │ │ ├── TestMongoRepository.cs │ │ ├── TestMongoRepositoryContext.cs │ │ ├── TestReadOnlyMongoRepository.cs │ │ ├── TestReadOnlyMongoRepositoryContext.cs │ │ └── UpdateDefinitionExtensions.cs │ ├── KeyTypedRepositoryTests/ │ │ ├── AddTests/ │ │ │ ├── AddManyAsyncTests.cs │ │ │ ├── AddManyTests.cs │ │ │ ├── AddOneAsyncTests.cs │ │ │ └── AddOneTests.cs │ │ ├── DeleteTests/ │ │ │ ├── DeleteManyAsyncTests.cs │ │ │ ├── DeleteManyTests.cs │ │ │ ├── DeleteOneAsyncTests.cs │ │ │ └── DeleteOneTests.cs │ │ ├── IndexTests/ │ │ │ ├── CreateAscendingIndexAsyncTests.cs │ │ │ ├── CreateCombinedTextIndexAsyncTests.cs │ │ │ ├── CreateDescendingIndexAsyncTests.cs │ │ │ ├── CreateHashedIndexAsyncTests.cs │ │ │ ├── CreateTextIndexAsyncTests.cs │ │ │ ├── DropIndexAsyncTests.cs │ │ │ └── GetIndexNamesAsyncTests.cs │ │ └── UpdateTests/ │ │ ├── UpdateManyAsyncTests.cs │ │ ├── UpdateManyTests.cs │ │ ├── UpdateOneAsyncTests.cs │ │ └── UpdateOneTests.cs │ ├── KeyedReadOnlyMongoRepositoryTests/ │ │ ├── AnyAsyncTests.cs │ │ ├── AnyTests.cs │ │ ├── CountAsyncTests.cs │ │ ├── CountTests.cs │ │ ├── GetAllAsyncTests.cs │ │ ├── GetAllTests.cs │ │ ├── GetByIdAsyncTests.cs │ │ ├── GetByIdTests.cs │ │ ├── GetByMaxAsyncTests.cs │ │ ├── GetByMaxTests.cs │ │ ├── GetByMinAsyncTests.cs │ │ ├── GetByMinTests.cs │ │ ├── GetMaxValueAsyncTests.cs │ │ ├── GetMaxValueTests.cs │ │ ├── GetMinValueAsyncTests.cs │ │ ├── GetMinValueTests.cs │ │ ├── GetOneAsyncTests.cs │ │ ├── GetOneTests.cs │ │ ├── GetSortedPaginatedAsyncTests.cs │ │ ├── GroupByTests.cs │ │ ├── ProjectManyAsyncTests.cs │ │ ├── ProjectManyTests.cs │ │ ├── ProjectOneAsyncTests.cs │ │ ├── ProjectOneTests.cs │ │ └── SumByAsyncTests.cs │ └── ReadOnlyMongoRepositoryTests/ │ ├── AnyAsyncTests.cs │ ├── AnyTests.cs │ ├── CountAsyncTests.cs │ ├── CountTests.cs │ ├── GetAllAsyncTests.cs │ ├── GetAllTests.cs │ ├── GetByIdAsyncTests.cs │ ├── GetByIdTests.cs │ ├── GetByMaxAsyncTests.cs │ ├── GetByMaxTests.cs │ ├── GetByMinAsyncTests.cs │ ├── GetByMinTests.cs │ ├── GetMaxValueAsyncTests.cs │ ├── GetMaxValueTests.cs │ ├── GetMinValueAsyncTests.cs │ ├── GetMinValueTests.cs │ ├── GetOneAsyncTests.cs │ ├── GetOneTests.cs │ ├── GetSortedPaginatedAsyncTests.cs │ ├── GroupByTests.cs │ ├── ProjectManyAsyncTests.cs │ ├── ProjectManyTests.cs │ ├── ProjectOneAsyncTests.cs │ ├── ProjectOneTests.cs │ └── SumByAsyncTests.cs ├── IntegrationTests/ │ ├── App.config │ ├── CRUDObjectIdTests.cs │ ├── CRUDPartitionedCollectionNameAttributeTests.cs │ ├── CRUDPartitionedTests.cs │ ├── CRUDTKeyPartitionedCollectionNameAttributeTests.cs │ ├── CRUDTKeyPartitionedTests.cs │ ├── CRUDTKeyTests.cs │ ├── CRUDTests.cs │ ├── Infrastructure/ │ │ ├── BaseMongoDbRepositoryTests.cs │ │ ├── GlobalVariables.cs │ │ ├── ITestRepository.cs │ │ ├── MongoDBDocumentTestBase.cs │ │ ├── MongoDbTKeyDocumentTestBase.cs │ │ ├── RandomExtensions.cs │ │ ├── TestClasses.cs │ │ └── TestRepository.cs │ ├── IntegrationTests.csproj │ ├── Properties/ │ │ └── AssemblyInfo.cs │ └── packages.config ├── LICENSE ├── MongoDbGenericRepository/ │ ├── Abstractions/ │ │ ├── IBaseMongoRepository.cs │ │ ├── IBaseMongoRepository_Update.cs │ │ ├── IBaseMongoRepository_Update_ClientSession.cs │ │ ├── IBaseReadOnlyRepository.cs │ │ ├── IMongoDbContext.cs │ │ ├── IReadOnlyMongoRepository.TKey.cs │ │ └── IReadOnlyMongoRepository.cs │ ├── Attributes/ │ │ └── CollectionNameAttribute.cs │ ├── BaseMongoRepository.Create.cs │ ├── BaseMongoRepository.Delete.cs │ ├── BaseMongoRepository.Index.cs │ ├── BaseMongoRepository.Main.cs │ ├── BaseMongoRepository.Update.ClientSession.cs │ ├── BaseMongoRepository.Update.cs │ ├── DataAccess/ │ │ ├── Base/ │ │ │ ├── DataAccessBase.cs │ │ │ └── IDataAccessBase.cs │ │ ├── Create/ │ │ │ ├── IMongoDbCreator.cs │ │ │ └── MongoDbCreator.cs │ │ ├── Delete/ │ │ │ ├── IMongoDbEraser.cs │ │ │ └── MongoDbEraser.cs │ │ ├── Index/ │ │ │ ├── IMongoDbIndexHandler.cs │ │ │ └── MongoDbIndexHandler.cs │ │ ├── Read/ │ │ │ ├── IMongoDbReader.cs │ │ │ ├── MongoDbReader.GroupBy.cs │ │ │ ├── MongoDbReader.Main.cs │ │ │ └── MongoDbReader.Project.cs │ │ └── Update/ │ │ ├── IMongoDbUpdater.cs │ │ ├── MongoDbUpdater.ClientSession.cs │ │ └── MongoDbUpdater.cs │ ├── IBaseMongoRepository.Create.cs │ ├── IBaseMongoRepository.Delete.cs │ ├── IBaseMongoRepository.Index.cs │ ├── Internals/ │ │ └── RepositorySerializationProvider.cs │ ├── KeyTypedRepository/ │ │ ├── BaseMongoRepository.TKey.Create.cs │ │ ├── BaseMongoRepository.TKey.Delete.cs │ │ ├── BaseMongoRepository.TKey.Index.cs │ │ ├── BaseMongoRepository.TKey.Main.cs │ │ ├── BaseMongoRepository.TKey.ReadOnly.cs │ │ ├── BaseMongoRepository.TKey.Update.cs │ │ ├── IBaseMongoRepository.TKey.Create.cs │ │ ├── IBaseMongoRepository.TKey.Delete.cs │ │ ├── IBaseMongoRepository.TKey.Index.cs │ │ ├── IBaseMongoRepository.TKey.Update.cs │ │ └── IBaseMongoRepository.TKey.cs │ ├── Models/ │ │ ├── Document.cs │ │ ├── IDocument.cs │ │ ├── IPartitionedDocument.cs │ │ ├── IndexCreationOptions.cs │ │ └── PartitionedDocument.cs │ ├── MongoDbContext.cs │ ├── MongoDbGenericRepository.csproj │ ├── MongoDbGenericRepository.xml │ ├── ReadOnlyMongoRepository.cs │ ├── Utils/ │ │ ├── IdGenerator.cs │ │ ├── Pluralization.cs │ │ └── RandomExtensions.cs │ └── _rels/ │ └── .rels ├── MongoDbGenericRepository.sln └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # Benchmark Results BenchmarkDotNet.Artifacts/ # .NET Core project.lock.json project.fragment.lock.json artifacts/ **/Properties/launchSettings.json *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # AxoCover is a Code Coverage Tool .axoCover/* !.axoCover/settings.json # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt *.appx # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Typescript v1 declaration files typings/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush .cr/ # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Tabs Studio *.tss # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs ================================================ FILE: CoreIntegrationTests/App.config ================================================  ================================================ FILE: CoreIntegrationTests/CRUDObjectIdTests.cs ================================================ using CoreIntegrationTests.Infrastructure; using MongoDB.Bson; namespace CoreIntegrationTests { public class CoreObjectIdTestDocument : TestDoc { } public class CRUDObjectIdTests : MongoDbTKeyDocumentTestBase { public CRUDObjectIdTests(MongoDbTestFixture fixture) : base(fixture) { } public override string GetClassName() { return "CRUDObjectIdTests"; } } } ================================================ FILE: CoreIntegrationTests/CRUDPartitionedCollectionNameAttributeTests.cs ================================================ using CoreIntegrationTests.Infrastructure; using MongoDbGenericRepository.Attributes; using MongoDbGenericRepository.Models; using System; namespace CoreIntegrationTests { [CollectionName("CoreTestingCNameAttrPart")] public class CorePartitionedCollectionNameDoc : TestDoc, IPartitionedDocument { public CorePartitionedCollectionNameDoc() { PartitionKey = "CoreTestPartitionKeyCollectionName"; } public string PartitionKey { get; set; } } public class CRUDPartitionedCollectionNameAttributeTests : MongoDbDocumentTestBase { public CRUDPartitionedCollectionNameAttributeTests(MongoDbTestFixture fixture) : base(fixture) { } public override string GetClassName() { return "CoreCRUDPartitionedCollectionNameAttributeTests"; } } } ================================================ FILE: CoreIntegrationTests/CRUDPartitionedTests.cs ================================================ using CoreIntegrationTests.Infrastructure; using MongoDbGenericRepository.Models; using System; namespace CoreIntegrationTests { public class CorePartitionedDoc : TestDoc, IPartitionedDocument { public CorePartitionedDoc() { PartitionKey = "CoreTestPartitionKey"; } public string PartitionKey { get; set; } } public class CRUDPartitionedTests : MongoDbDocumentTestBase { public CRUDPartitionedTests(MongoDbTestFixture fixture) : base(fixture) { } public override string GetClassName() { return "CoreCRUDPartitionedTests"; } } } ================================================ FILE: CoreIntegrationTests/CRUDTKeyPartitionedCollectionNameAttributeTests.cs ================================================ using CoreIntegrationTests.Infrastructure; using MongoDB.Bson; using MongoDbGenericRepository.Attributes; using MongoDbGenericRepository.Models; using System; namespace CoreIntegrationTests { #region Guid Type [CollectionName("TestingCNameAttrPartTKey")] public class CoreTKeyPartitionedCollectionNameDoc : TestDoc, IPartitionedDocument { public CoreTKeyPartitionedCollectionNameDoc() { PartitionKey = "CoreTestPartitionKey"; } public string PartitionKey { get; set; } } public class CRUDTKeyPartitionedCollectionNameAttributeTests : MongoDbTKeyDocumentTestBase { public CRUDTKeyPartitionedCollectionNameAttributeTests(MongoDbTestFixture fixture) : base(fixture) { } public override string GetClassName() { return "CoreCRUDTKeyPartitionedCollectionNameAttributeTests"; } } #endregion Guid Type #region ObjectId Type [CollectionName("TestingCNameAttrPartObjectId")] public class CoreObjectIdPartitionedCollectionNameDoc : TestDoc, IPartitionedDocument { public CoreObjectIdPartitionedCollectionNameDoc() { PartitionKey = "CoreTestPartitionKeyObjectId"; } public string PartitionKey { get; set; } } public class CRUDObjectIdPartitionedCollectionNameAttributeTests : MongoDbTKeyDocumentTestBase { public CRUDObjectIdPartitionedCollectionNameAttributeTests(MongoDbTestFixture fixture) : base(fixture) { } public override string GetClassName() { return "CoreCRUDTKeyPartitionedCollectionNameAttributeTests"; } } #endregion ObjectId Type } ================================================ FILE: CoreIntegrationTests/CRUDTKeyPartitionedTests.cs ================================================ using CoreIntegrationTests.Infrastructure; using MongoDbGenericRepository.Models; using System; namespace CoreIntegrationTests { public class CorePartitionedTKeyTestDocument : TestDoc, IPartitionedDocument { public CorePartitionedTKeyTestDocument() { PartitionKey = "CoreTestPartitionKey"; } public string PartitionKey { get; set; } } public class CRUDTKeyPartitionedTests : MongoDbTKeyDocumentTestBase { public CRUDTKeyPartitionedTests(MongoDbTestFixture fixture) : base(fixture) { } public override string GetClassName() { return "CoreCRUDTKeyPartitionedTests"; } } } ================================================ FILE: CoreIntegrationTests/CRUDTKeyTests.cs ================================================ using CoreIntegrationTests.Infrastructure; using System; namespace CoreIntegrationTests { public class CoreTKeyTestDocument : TestDoc { } public class CRUDTKeyTests : MongoDbTKeyDocumentTestBase { public CRUDTKeyTests(MongoDbTestFixture fixture) : base(fixture) { } public override string GetClassName() { return "CreateTKeyTests"; } } } ================================================ FILE: CoreIntegrationTests/CRUDTests.cs ================================================ using CoreIntegrationTests.Infrastructure; using System; namespace CoreIntegrationTests { public class CoreTestDocument : TestDoc { } public class CRUDTests : MongoDbDocumentTestBase { public CRUDTests(MongoDbTestFixture fixture) : base(fixture) { } public override string GetClassName() { return "CRUDTests"; } } } ================================================ FILE: CoreIntegrationTests/CoreIntegrationTests.csproj ================================================  net8.0 disable enable all runtime; build; native; contentfiles; analyzers all runtime; build; native; contentfiles; analyzers; buildtransitive Always ================================================ FILE: CoreIntegrationTests/IdentityUserTests.cs ================================================ using CoreIntegrationTests.Infrastructure; using MongoDbGenericRepository.Models; using System; using System.Collections.Generic; using Xunit; using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; namespace CoreIntegrationTests { public class MongoIdentityUser : IdentityUser, IDocument where TKey : IEquatable { public int Version { get; set; } } public class IdentityUserTest : MongoIdentityUser, IDocument { public IdentityUserTest() { Id = Guid.NewGuid(); Version = 2; } public string SomeContent { get; set; } } public class IdentityUserTests : BaseMongoDbRepositoryTests { [Fact] public void AddOne() { // Arrange var document = new IdentityUserTest(); // Act SUT.AddOne(document); // Assert long count = SUT.Count(e => e.Id == document.Id); Assert.Equal(1, count); } [Fact] public async Task AddOneAsync() { // Arrange var document = new IdentityUserTest(); // Act await SUT.AddOneAsync(document); // Assert long count = SUT.Count(e => e.Id == document.Id); Assert.Equal(1, count); } [Fact] public void AddMany() { // Arrange var documents = new List { new IdentityUserTest(), new IdentityUserTest() }; // Act SUT.AddMany(documents); // Assert long count = SUT.Count(e => e.Id == documents[0].Id || e.Id == documents[1].Id); Assert.Equal(2, count); } [Fact] public async Task AddManyAsync() { // Arrange var documents = new List { new IdentityUserTest(), new IdentityUserTest() }; // Act await SUT.AddManyAsync(documents); // Assert long count = SUT.Count(e => e.Id == documents[0].Id || e.Id == documents[1].Id); Assert.Equal(2, count); } } } ================================================ FILE: CoreIntegrationTests/Infrastructure/BaseMongoDbRepositoryTests.cs ================================================ using MongoDbGenericRepository.Models; using System.Collections.Generic; using System; namespace CoreIntegrationTests.Infrastructure { public class BaseMongoDbRepositoryTests : IDisposable where T : new() { public T CreateTestDocument() { return new T(); } public List CreateTestDocuments(int numberOfDocumentsToCreate) { var docs = new List(); for(var i = 0; i < numberOfDocumentsToCreate; i++) { docs.Add(new T()); } return docs; } /// /// Constructor, init code /// public BaseMongoDbRepositoryTests() { Init(); var type = CreateTestDocument(); if (type is IPartitionedDocument) { PartitionKey = ((IPartitionedDocument)type).PartitionKey; } } public string PartitionKey { get; set; } /// /// SUT: System Under Test /// protected static ITestRepository SUT { get; set; } public void Init() { MongoDbConfig.EnsureConfigured(); SUT = TestRepository.Instance; } public void Cleanup() { // We drop the collection at the end of each test session. if (!string.IsNullOrEmpty(PartitionKey)) { SUT.DropTestCollection(PartitionKey); } else { SUT.DropTestCollection(); } } #region IDisposable Support private bool _disposedValue; // Pour détecter les appels redondants protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { Cleanup(); } _disposedValue = true; } } // Ce code est ajouté pour implémenter correctement le modèle supprimable. public void Dispose() { // Ne modifiez pas ce code. Placez le code de nettoyage dans Dispose(bool disposing) ci-dessus. Dispose(true); } #endregion } } ================================================ FILE: CoreIntegrationTests/Infrastructure/GlobalVariables.cs ================================================ using System; namespace CoreIntegrationTests.Infrastructure { /// /// A class holding global variables. /// public static class GlobalVariables { /// /// A random number generator. /// public static Random Random = new Random(); } } ================================================ FILE: CoreIntegrationTests/Infrastructure/ITestRepository.cs ================================================ using MongoDbGenericRepository; namespace CoreIntegrationTests { public interface ITestRepository : IBaseMongoRepository { void DropTestCollection(); void DropTestCollection(string partitionKey); } } ================================================ FILE: CoreIntegrationTests/Infrastructure/MongoDbConfig.cs ================================================ using MongoDB.Bson.Serialization.Conventions; using System.Threading; namespace CoreIntegrationTests.Infrastructure { internal static class MongoDbConfig { private static bool _initialized; private static object _initializationLock = new(); private static object _initializationTarget; public static void EnsureConfigured() { EnsureConfiguredImpl(); } private static void EnsureConfiguredImpl() { LazyInitializer.EnsureInitialized(ref _initializationTarget, ref _initialized, ref _initializationLock, () => { Configure(); return null; }); } private static void Configure() { RegisterConventions(); } private static void RegisterConventions() { var pack = new ConventionPack { new IgnoreIfNullConvention(false), new CamelCaseElementNameConvention(), }; } } } ================================================ FILE: CoreIntegrationTests/Infrastructure/MongoDbDocumentTestBase.Main.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.Models; using Xunit; namespace CoreIntegrationTests.Infrastructure { public abstract partial class MongoDbDocumentTestBase where T : TestDoc, new() { private readonly MongoDbTestFixture _fixture; protected MongoDbDocumentTestBase(MongoDbTestFixture fixture) { _fixture = fixture; var type = CreateTestDocument(); DocumentTypeName = type.GetType().FullName; if (type is IPartitionedDocument) { PartitionKey = ((IPartitionedDocument)type).PartitionKey; } _fixture.PartitionKey = PartitionKey; TestClassName = GetClassName(); MongoDbConfig.EnsureConfigured(); SUT = TestTKeyRepository.Instance; } protected T CreateTestDocument() { return _fixture.CreateTestDocument(); } public abstract string GetClassName(); protected List CreateTestDocuments(int numberOfDocumentsToCreate) { return _fixture.CreateTestDocuments(numberOfDocumentsToCreate); } /// /// The partition key for the collection, if any /// protected string PartitionKey { get; set; } /// /// the name of the test class /// protected string TestClassName { get; set; } /// /// The name of the document used for tests /// protected string DocumentTypeName { get; set; } /// /// SUT: System Under Test /// protected static ITestRepository SUT { get; set; } #region Add [Fact] public void AddOne() { // Arrange var document = CreateTestDocument(); // Act SUT.AddOne(document); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(document.Id)) : SUT.Count(e => e.Id.Equals(document.Id), PartitionKey); Assert.True(1 == count, GetTestName()); } [Fact] public async Task AddOneAsync() { // Arrange var document = CreateTestDocument(); // Act await SUT.AddOneAsync(document); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(document.Id)) : SUT.Count(e => e.Id.Equals(document.Id), PartitionKey); Assert.True(1 == count, GetTestName()); } [Fact] public void AddMany() { // Arrange var documents = CreateTestDocuments(2); // Act SUT.AddMany(documents); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id)) : SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); Assert.True(2 == count, GetTestName()); } [Fact] public void AddManyWithDifferentPartitionKey() { // only run this test for tests on documents with partition key if (!string.IsNullOrEmpty(PartitionKey)) { // Arrange var documents = CreateTestDocuments(4); if (documents.Any(e => e is IPartitionedDocument)) { var secondPartitionKey = $"{PartitionKey}-2"; ((IPartitionedDocument)documents[2]).PartitionKey = secondPartitionKey; ((IPartitionedDocument)documents[3]).PartitionKey = secondPartitionKey; // Act SUT.AddMany(documents); // Assert long count = SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); long secondPartitionCount = SUT.Count(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey); // Cleanup second partition SUT.DeleteMany(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey); Assert.True(2 == count, GetTestName()); Assert.True(2 == secondPartitionCount, GetTestName()); } } } [Fact] public async Task AddManyAsync() { // Arrange var documents = CreateTestDocuments(2); // Act await SUT.AddManyAsync(documents); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id)) : SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); Assert.True(2 == count, GetTestName()); } [Fact] public async Task AddManyAsyncWithDifferentPartitionKey() { // only run this test for tests on documents with partition key if (!string.IsNullOrEmpty(PartitionKey)) { // Arrange var documents = CreateTestDocuments(4); if (documents.Any(e => e is IPartitionedDocument)) { var secondPartitionKey = $"{PartitionKey}-2"; ((IPartitionedDocument)documents[2]).PartitionKey = secondPartitionKey; ((IPartitionedDocument)documents[3]).PartitionKey = secondPartitionKey; // Act await SUT.AddManyAsync(documents); // Assert long count = SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); long secondPartitionCount = SUT.Count(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey); // Cleanup second partition SUT.DeleteMany(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey); Assert.True(2 == count, GetTestName()); Assert.True(2 == secondPartitionCount, GetTestName()); } } } #endregion Add #region Read [Fact] public async Task GetByIdAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.GetByIdAsync(document.Id, PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public void GetById() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.GetById(document.Id, PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public async Task GetOneAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.GetOneAsync(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public void GetOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.GetOne(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public void GetCursor() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var cursor = SUT.GetCursor(x => x.Id.Equals(document.Id), PartitionKey); var count = cursor.CountDocuments(); // Assert Assert.True(1 == count, GetTestName()); } [Fact] public async Task AnyAsyncReturnsTrue() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.AnyAsync(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(result, GetTestName()); } [Fact] public async Task AnyAsyncReturnsFalse() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.AnyAsync(x => x.Id.Equals(Guid.NewGuid()), PartitionKey); // Assert Assert.False(result, GetTestName()); } [Fact] public void AnyReturnsTrue() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(result, GetTestName()); } [Fact] public void AnyReturnsFalse() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(x => x.Id.Equals(Guid.NewGuid()), PartitionKey); // Assert Assert.False(result, GetTestName()); } [Fact] public async Task GetAllAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = await SUT.GetAllAsync(x => x.SomeContent == content, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); } [Fact] public void GetAll() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.GetAll(x => x.SomeContent == content, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); } [Fact] public async Task CountAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = await SUT.CountAsync(x => x.SomeContent == content, PartitionKey); // Assert Assert.True(5 == result, GetTestName()); } [Fact] public void Count() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.Count(x => x.SomeContent == content, PartitionKey); // Assert Assert.True(5 == result, GetTestName()); } #endregion Read #region Delete [Fact] public void DeleteOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.DeleteOne(document); // Assert Assert.True(1 == result); Assert.False(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), GetTestName()); } [Fact] public void DeleteOneLinq() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.DeleteOne(e => e.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(1 == result); Assert.False(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), GetTestName()); } [Fact] public async Task DeleteOneAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.DeleteOneAsync(document); // Assert Assert.True(1 == result); Assert.False(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), GetTestName()); } [Fact] public async Task DeleteOneAsyncLinq() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.DeleteOneAsync(e => e.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(1 == result); Assert.False(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), GetTestName()); } [Fact] public async Task DeleteManyAsyncLinq() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); SUT.AddMany(documents); // Act var result = await SUT.DeleteManyAsync(e => e.SomeContent == criteria, PartitionKey); // Assert Assert.True(5 == result); Assert.False(SUT.Any(e => e.SomeContent == criteria, PartitionKey), GetTestName()); } [Fact] public async Task DeleteManyAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); var canPartition = !string.IsNullOrEmpty(PartitionKey) && documents.Any(e => e is IPartitionedDocument); string secondKey = null; if (canPartition) { secondKey = $"{PartitionKey}-2"; ((IPartitionedDocument)documents[3]).PartitionKey = secondKey; ((IPartitionedDocument)documents[4]).PartitionKey = secondKey; } SUT.AddMany(documents); // Act var result = await SUT.DeleteManyAsync(documents); // Assert Assert.True(5 == result); Assert.False(SUT.Any(e => e.SomeContent == criteria, PartitionKey), GetTestName()); if (canPartition) { Assert.False(SUT.Any(e => e.SomeContent == criteria, secondKey), GetTestName()); } } [Fact] public void DeleteManyLinq() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); SUT.AddMany(documents); // Act var result = SUT.DeleteMany(e => e.SomeContent == criteria, PartitionKey); // Assert Assert.True(5 == result); Assert.False(SUT.Any(e => e.SomeContent == criteria, PartitionKey), GetTestName()); } [Fact] public void DeleteMany() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); var canPartition = !string.IsNullOrEmpty(PartitionKey) && documents.Any(e => e is IPartitionedDocument); string secondKey = null; if (canPartition) { secondKey = $"{PartitionKey}-2"; ((IPartitionedDocument)documents[3]).PartitionKey = secondKey; ((IPartitionedDocument)documents[4]).PartitionKey = secondKey; } SUT.AddMany(documents); // Act var result = SUT.DeleteMany(documents); // Assert Assert.True(5 == result); Assert.False(SUT.Any(e => e.SomeContent == criteria, PartitionKey), GetTestName()); if (canPartition) { Assert.False(SUT.Any(e => e.SomeContent == criteria, secondKey), GetTestName()); } } #endregion Delete #region Project [Fact] public async Task ProjectOneAsync() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var document = CreateTestDocument(); document.SomeContent = someContent; document.Nested.SomeDate = someDate; SUT.AddOne(document); // Act var result = await SUT.ProjectOneAsync( x => x.Id.Equals(document.Id), x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.True(null != result, GetTestName()); Assert.True(someContent == result.SomeContent, GetTestName()); Assert.True(someDate.Minute == result.SomeDate.Minute, GetTestName()); Assert.True(someDate.Second == result.SomeDate.Second, GetTestName()); } [Fact] public void ProjectOne() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var document = CreateTestDocument(); document.SomeContent = someContent; document.Nested.SomeDate = someDate; SUT.AddOne(document); // Act var result = SUT.ProjectOne( x => x.Id.Equals(document.Id), x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.True(null != result, GetTestName()); Assert.True(someContent == result.SomeContent, GetTestName()); Assert.True(someDate.Minute == result.SomeDate.Minute, GetTestName()); Assert.True(someDate.Second == result.SomeDate.Second, GetTestName()); } [Fact] public async Task ProjectManyAsync() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var documents = CreateTestDocuments(5); documents.ForEach(e => { e.SomeContent = someContent; e.Nested.SomeDate = someDate; }); SUT.AddMany(documents); // Act var result = await SUT.ProjectManyAsync( x => x.SomeContent == someContent, x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); Assert.True(someContent == result.First().SomeContent, GetTestName()); Assert.True(someDate.Minute == result.First().SomeDate.Minute, GetTestName()); Assert.True(someDate.Second == result.First().SomeDate.Second, GetTestName()); } [Fact] public void ProjectMany() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var documents = CreateTestDocuments(5); documents.ForEach(e => { e.SomeContent = someContent; e.Nested.SomeDate = someDate; }); SUT.AddMany(documents); // Act var result = SUT.ProjectMany( x => x.SomeContent == someContent, x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); Assert.True(someContent == result.First().SomeContent, GetTestName()); Assert.True(someDate.Minute == result.First().SomeDate.Minute, GetTestName()); Assert.True(someDate.Second == result.First().SomeDate.Second, GetTestName()); } #endregion Project #region Max / Min Queries [Fact] public async Task GetByMaxAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First(); // Act var result = await SUT.GetByMaxAsync(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.NotNull(result); Assert.Equal(expectedMax.Id, result.Id); } [Fact] public void GetByMax() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First(); // Act var result = SUT.GetByMax(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.NotNull(result); Assert.Equal(expectedMax.Id, result.Id); } [Fact] public async Task GetByMinAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First(); // Act var result = await SUT.GetByMinAsync(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.NotNull(result); Assert.Equal(expectedMin.Id, result.Id); } [Fact] public void GetByMin() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First(); // Act var result = SUT.GetByMin(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.NotNull(result); Assert.Equal(expectedMin.Id, result.Id); } [Fact] public void GetMinValue() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First(); // Act var result = SUT.GetMinValue(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.True(result != default(DateTime)); Assert.Equal(expectedMin.Nested.SomeDate.Date, result.Date); } [Fact] public async Task GetMinValueAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First(); // Act var result = await SUT.GetMinValueAsync(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.True(result != default(DateTime)); Assert.Equal(expectedMin.Nested.SomeDate.Date, result.Date); } [Fact] public void GetMaxValue() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First(); // Act var result = SUT.GetMaxValue(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.True(result != default(DateTime)); Assert.Equal(expectedMax.Nested.SomeDate.Date, result.Date); } [Fact] public async Task GetMaxValueAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMin = documents.OrderByDescending(e => e.Nested.SomeDate).First(); // Act var result = await SUT.GetMaxValueAsync(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.True(result != default(DateTime)); Assert.Equal(expectedMin.Nested.SomeDate.Date, result.Date); } #endregion Max / Min Queries #region Index Management static SemaphoreSlim textIndexSemaphore = new SemaphoreSlim(1, 1); [Fact] public async Task CreateTextIndexNoOptionAsync() { // Arrange const string expectedIndexName = "SomeContent_text"; // Act await textIndexSemaphore.WaitAsync(); try { var result = await SUT.CreateTextIndexAsync(x => x.SomeContent, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } finally { textIndexSemaphore.Release(); } } [Fact] public async Task CreateTextIndexWithOptionAsync() { // Arrange string expectedIndexName = $"{Guid.NewGuid()}"; var option = new IndexCreationOptions { Name = expectedIndexName }; await textIndexSemaphore.WaitAsync(); try { // Act var result = await SUT.CreateTextIndexAsync(x => x.AddedAtUtc, option, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } finally { textIndexSemaphore.Release(); } } [Fact] public async Task CreateAscendingIndexAsync() { // Arrange const string expectedIndexName = "SomeContent_1"; // Act var result = await SUT.CreateAscendingIndexAsync(x => x.SomeContent, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } [Fact] public async Task CreateDescendingIndexAsync() { // Arrange const string expectedIndexName = "SomeContent_-1"; // Act var result = await SUT.CreateDescendingIndexAsync(x => x.SomeContent, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } [Fact] public async Task CreateHashedIndexAsync() { // Arrange const string expectedIndexName = "SomeContent_hashed"; // Act var result = await SUT.CreateHashedIndexAsync(x => x.SomeContent, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } [Fact] public async Task CreateCombinedTextIndexAsync() { // Arrange const string expectedIndexName = "SomeContent2_text_SomeContent3_text"; // Act Expression > ex = x => x.SomeContent2; Expression > ex2 = x => x.SomeContent3; var result = await SUT.CreateCombinedTextIndexAsync(new[] { ex, ex2 }, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } #endregion Index Management #region Math [Fact] public async Task SumByDecimalAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.Nested.SomeAmount = 5m; e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedSum = documents.Sum(e => e.Nested.SomeAmount); // Act var result = await SUT.SumByAsync(e => e.SomeContent == criteria, e => e.Nested.SomeAmount, PartitionKey); // Assert Assert.Equal(expectedSum, result); } [Fact] public void SumByDecimal() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.Nested.SomeAmount = 5m; e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedSum = documents.Sum(e => e.Nested.SomeAmount); // Act var result = SUT.SumBy(e => e.SomeContent == criteria, e => e.Nested.SomeAmount, PartitionKey); // Assert Assert.Equal(expectedSum, result); } #endregion Math #region Test Utils [MethodImpl(MethodImplOptions.NoInlining)] private string GetCurrentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(1); return sf.GetMethod().Name; } [MethodImpl(MethodImplOptions.NoInlining)] private string GetParentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(2); var method = sf.GetMethod().DeclaringType.Name; return method; } private string GetTestName() { return $"{TestClassName}{PartitionKey}.{GetParentMethod()}"; } private string GetContent() { return $"{TestClassName}{PartitionKey}.{Guid.NewGuid()}.{GetParentMethod()}"; } private void Cleanup() { // We drop the collection at the end of each test session. if (!string.IsNullOrEmpty(PartitionKey)) { SUT.DropTestCollection(PartitionKey); } else { SUT.DropTestCollection(); } } #endregion Test Utils } } ================================================ FILE: CoreIntegrationTests/Infrastructure/MongoDbDocumentTestBase.Update.cs ================================================ using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Xunit; namespace CoreIntegrationTests.Infrastructure { public abstract partial class MongoDbDocumentTestBase : IClassFixture> where T : TestDoc, new() { #region Update One [Fact] public void UpdateOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); document.SomeContent = content; // Act var result = SUT.UpdateOne(document); // Assert Assert.True(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public async Task UpdateOneAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); document.SomeContent = content; // Act var result = await SUT.UpdateOneAsync(document); // Assert Assert.True(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public void UpdateOneField() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = SUT.UpdateOne(document, x => x.SomeContent, content); // Assert Assert.True(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public async Task UpdateOneFieldAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = await SUT.UpdateOneAsync(document, x => x.SomeContent, content); // Assert Assert.True(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public void UpdateOneFieldWithFilter() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = SUT.UpdateOne(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public async Task UpdateOneFieldWithFilterAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = await SUT.UpdateOneAsync(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public async Task UpdateOneAsyncWithUpdateDefinition() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = MongoDB.Driver.Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); // Act var result = await SUT.UpdateOneAsync(document, updateDef); // Assert Assert.True(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument); Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); } [Fact] public void UpdateOneWithUpdateDefinition() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = MongoDB.Driver.Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); // Act var result = SUT.UpdateOne(document, updateDef); // Assert Assert.True(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument); Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); } #endregion Update One #region Update Many [Fact] public async Task UpdateManyWithLinqFilterAsync() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var content = GetContent(); // Act var result = await SUT.UpdateManyAsync(x => docIds.Contains(x.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocument = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocument.Count == 2); Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName()); } [Fact] public async Task UpdateManyWithFilterDefinitionAsync() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var filterDefinition = Builders.Filter.Where(x => docIds.Contains(x.Id)); var content = GetContent(); // Act var result = await SUT.UpdateManyAsync(filterDefinition, x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocument = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocument.Count == 2); Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName()); } [Fact] public async Task UpdateManyWithLinqFilterAndUpdateDefinitionAsync() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); var content = GetContent(); // Act var result = await SUT.UpdateManyAsync(x => docIds.Contains(x.Id), updateDef, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocuments = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocuments.Count == 2); updatedDocuments.ForEach(updatedDocument => { Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); }); } [Fact] public async Task UpdateManyWithFilterAndUpdateDefinitionsAsync() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); var docIds = documents.Select(u => u.Id).ToArray(); var filterDefinition = Builders.Filter.Where(x => docIds.Contains(x.Id)); var content = GetContent(); // Act var result = await SUT.UpdateManyAsync(filterDefinition, updateDef, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocuments = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocuments.Count == 2); updatedDocuments.ForEach(updatedDocument => { Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); }); } [Fact] public void UpdateManyWithLinqFilter() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var content = GetContent(); // Act var result = SUT.UpdateMany(x => docIds.Contains(x.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocument = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocument.Count == 2); Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName()); } [Fact] public void UpdateManyWithFilterDefinition() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var filterDefinition = Builders.Filter.Where(x => docIds.Contains(x.Id)); var content = GetContent(); // Act var result = SUT.UpdateMany(filterDefinition, x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocument = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocument.Count == 2); Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName()); } [Fact] public void UpdateManyWithLinqFilterAndUpdateDefinition() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); var content = GetContent(); // Act var result = SUT.UpdateMany(x => docIds.Contains(x.Id), updateDef, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocuments = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocuments.Count == 2); updatedDocuments.ForEach(updatedDocument => { Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); }); } [Fact] public void UpdateManyWithFilterAndUpdateDefinitions() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); var docIds = documents.Select(u => u.Id).ToArray(); var filterDefinition = Builders.Filter.Where(x => docIds.Contains(x.Id)); var content = GetContent(); // Act var result = SUT.UpdateMany(filterDefinition, updateDef, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocuments = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocuments.Count == 2); updatedDocuments.ForEach(updatedDocument => { Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); }); } #endregion Update Many } } ================================================ FILE: CoreIntegrationTests/Infrastructure/MongoDbTKeyDocumentTestBase.Main.cs ================================================ using MongoDB.Driver; using MongoDbGenericRepository.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Xunit; namespace CoreIntegrationTests.Infrastructure { public abstract partial class MongoDbTKeyDocumentTestBase : IClassFixture> where T : TestDoc, new() where TKey : IEquatable { private readonly MongoDbTestFixture _fixture; protected MongoDbTKeyDocumentTestBase(MongoDbTestFixture fixture) { _fixture = fixture; var type = CreateTestDocument(); DocumentTypeName = type.GetType().FullName; if (type is IPartitionedDocument) { PartitionKey = ((IPartitionedDocument)type).PartitionKey; } _fixture.PartitionKey = PartitionKey; TestClassName = GetClassName(); MongoDbConfig.EnsureConfigured(); SUT = TestRepository.Instance; } public abstract string GetClassName(); public T CreateTestDocument() { return _fixture.CreateTestDocument(); } public List CreateTestDocuments(int numberOfDocumentsToCreate) { return _fixture.CreateTestDocuments(numberOfDocumentsToCreate); } /// /// The partition key for the collection, if any /// protected string PartitionKey { get; set; } /// /// the name of the test class /// protected string TestClassName { get; set; } /// /// The name of the document used for tests /// protected string DocumentTypeName { get; set; } /// /// SUT: System Under Test /// protected static ITestRepository SUT { get; set; } #region Add [Fact] public void AddOne() { // Arrange var document = CreateTestDocument(); // Act SUT.AddOne(document); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(document.Id)) : SUT.Count(e => e.Id.Equals(document.Id), PartitionKey); Assert.True(1 == count, GetTestName()); } [Fact] public async Task AddOneAsync() { // Arrange var document = CreateTestDocument(); // Act await SUT.AddOneAsync(document); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(document.Id)) : SUT.Count(e => e.Id.Equals(document.Id), PartitionKey); Assert.True(1 == count, GetTestName()); } [Fact] public void AddMany() { // Arrange var documents = CreateTestDocuments(2); // Act SUT.AddMany(documents); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id)) : SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); Assert.True(2 == count, GetTestName()); } [Fact] public void AddManyWithDifferentPartitionKey() { // only run this test for tests on documents with partition key if (!string.IsNullOrEmpty(PartitionKey)) { // Arrange var documents = CreateTestDocuments(4); if (documents.Any(e => e is IPartitionedDocument)) { var secondPartitionKey = $"{PartitionKey}-2"; ((IPartitionedDocument)documents[2]).PartitionKey = secondPartitionKey; ((IPartitionedDocument)documents[3]).PartitionKey = secondPartitionKey; // Act SUT.AddMany(documents); // Assert long count = SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); long secondPartitionCount = SUT.Count(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey); // Cleanup second partition SUT.DeleteMany(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey); Assert.True(2 == count, GetTestName()); Assert.True(2 == secondPartitionCount, GetTestName()); } } } [Fact] public async Task AddManyAsync() { // Arrange var documents = CreateTestDocuments(2); // Act await SUT.AddManyAsync(documents); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id)) : SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); Assert.True(2 == count, GetTestName()); } [Fact] public async Task AddManyAsyncWithDifferentPartitionKey() { // only run this test for tests on documents with partition key if (!string.IsNullOrEmpty(PartitionKey)) { // Arrange var documents = CreateTestDocuments(4); if (documents.Any(e => e is IPartitionedDocument)) { var secondPartitionKey = $"{PartitionKey}-2"; ((IPartitionedDocument)documents[2]).PartitionKey = secondPartitionKey; ((IPartitionedDocument)documents[3]).PartitionKey = secondPartitionKey; // Act await SUT.AddManyAsync(documents); // Assert long count = SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); long secondPartitionCount = SUT.Count(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey); // Cleanup second partition SUT.DeleteMany(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey); Assert.True(2 == count, GetTestName()); Assert.True(2 == secondPartitionCount, GetTestName()); } } } #endregion Add #region Read [Fact] public async Task GetByIdAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.GetByIdAsync(document.Id, PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public void GetById() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.GetById(document.Id, PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public async Task GetOneByFilterDefinitionAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.GetOneAsync(Builders.Filter.Eq(x => x.Id, document.Id), null, PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public void GetOneByFilterDefinition() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.GetOne(Builders.Filter.Eq(x => x.Id, document.Id), null, PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public async Task GetOneAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.GetOneAsync(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public void GetOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.GetOne(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(null != result, GetTestName()); } [Fact] public void GetCursor() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var cursor = SUT.GetCursor(x => x.Id.Equals(document.Id), PartitionKey); var count = cursor.CountDocuments(); // Assert Assert.True(1 == count, GetTestName()); } [Fact] public async Task AnyAsyncByDefinitionReturnsTrue() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.AnyAsync(Builders.Filter.Eq(x => x.Id, document.Id), null, PartitionKey); // Assert Assert.True(result, GetTestName()); } [Fact] public async Task AnyAsyncByDefinitionReturnsFalse() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.AnyAsync(Builders.Filter.Eq(x => x.Id, document.Init()), null, PartitionKey); // Assert Assert.False(result, GetTestName()); } [Fact] public async Task AnyAsyncReturnsTrue() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.AnyAsync(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(result, GetTestName()); } [Fact] public async Task AnyAsyncReturnsFalse() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.AnyAsync(x => x.Id.Equals(document.Init()), PartitionKey); // Assert Assert.False(result, GetTestName()); } [Fact] public void AnyByDefinitionReturnsTrue() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(Builders.Filter.Eq(x => x.Id, document.Id), null, PartitionKey); // Assert Assert.True(result, GetTestName()); } [Fact] public void AnyByDefinitionReturnsFalse() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(Builders.Filter.Eq(x => x.Id, document.Init()), null, PartitionKey); // Assert Assert.False(result, GetTestName()); } [Fact] public void AnyReturnsTrue() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(result, GetTestName()); } [Fact] public void AnyReturnsFalse() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(x => x.Id.Equals(document.Init()), PartitionKey); // Assert Assert.False(result, GetTestName()); } [Fact] public async Task GetAllByDefinitionAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = await SUT.GetAllAsync(Builders.Filter.Eq(x => x.SomeContent, content), null, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); } [Fact] public void GetAllByDefinition() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.GetAll(Builders.Filter.Eq(x => x.SomeContent, content), null, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); } [Fact] public async Task GetAllAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = await SUT.GetAllAsync(x => x.SomeContent == content, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); } [Fact] public void GetAll() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.GetAll(x => x.SomeContent == content, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); } [Fact] public async Task CountByDefinitionAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = await SUT.CountAsync(Builders.Filter.Eq(x => x.SomeContent, content), null, PartitionKey); // Assert Assert.True(5 == result, GetTestName()); } [Fact] public void CountByDefinition() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.Count(Builders.Filter.Eq(x => x.SomeContent, content), null, PartitionKey); // Assert Assert.True(5 == result, GetTestName()); } [Fact] public async Task CountAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = await SUT.CountAsync(x => x.SomeContent == content, PartitionKey); // Assert Assert.True(5 == result, GetTestName()); } [Fact] public void Count() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.Count(x => x.SomeContent == content, PartitionKey); // Assert Assert.True(5 == result, GetTestName()); } #endregion Read #region Delete [Fact] public void DeleteOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.DeleteOne(document); // Assert Assert.True(1 == result); Assert.False(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), GetTestName()); } [Fact] public void DeleteOneLinq() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.DeleteOne(e => e.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(1 == result); Assert.False(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), GetTestName()); } [Fact] public async Task DeleteOneAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.DeleteOneAsync(document); // Assert Assert.True(1 == result); Assert.False(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), GetTestName()); } [Fact] public async Task DeleteOneAsyncLinq() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = await SUT.DeleteOneAsync(e => e.Id.Equals(document.Id), PartitionKey); // Assert Assert.True(1 == result); Assert.False(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), GetTestName()); } [Fact] public async Task DeleteManyAsyncLinq() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); SUT.AddMany(documents); // Act var result = await SUT.DeleteManyAsync(e => e.SomeContent == criteria, PartitionKey); // Assert Assert.True(5 == result); Assert.False(SUT.Any(e => e.SomeContent == criteria, PartitionKey), GetTestName()); } [Fact] public async Task DeleteManyAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); var canPartition = !string.IsNullOrEmpty(PartitionKey) && documents.Any(e => e is IPartitionedDocument); string secondKey = null; if (canPartition) { secondKey = $"{PartitionKey}-2"; ((IPartitionedDocument)documents[3]).PartitionKey = secondKey; ((IPartitionedDocument)documents[4]).PartitionKey = secondKey; } SUT.AddMany(documents); // Act var result = await SUT.DeleteManyAsync(documents); // Assert Assert.True(5 == result); Assert.False(SUT.Any(e => e.SomeContent == criteria, PartitionKey), GetTestName()); if (canPartition) { Assert.False(SUT.Any(e => e.SomeContent == criteria, secondKey), GetTestName()); } } [Fact] public void DeleteManyLinq() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); SUT.AddMany(documents); // Act var result = SUT.DeleteMany(e => e.SomeContent == criteria, PartitionKey); // Assert Assert.True(5 == result); Assert.False(SUT.Any(e => e.SomeContent == criteria, PartitionKey), GetTestName()); } [Fact] public void DeleteMany() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); var canPartition = !string.IsNullOrEmpty(PartitionKey) && documents.Any(e => e is IPartitionedDocument); string secondKey = null; if (canPartition) { secondKey = $"{PartitionKey}-2"; ((IPartitionedDocument)documents[3]).PartitionKey = secondKey; ((IPartitionedDocument)documents[4]).PartitionKey = secondKey; } SUT.AddMany(documents); // Act var result = SUT.DeleteMany(documents); // Assert Assert.True(5 == result); Assert.False(SUT.Any(e => e.SomeContent == criteria, PartitionKey), GetTestName()); if (canPartition) { Assert.False(SUT.Any(e => e.SomeContent == criteria, secondKey), GetTestName()); } } #endregion Delete #region Project [Fact] public async Task ProjectOneAsync() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var document = CreateTestDocument(); document.SomeContent = someContent; document.Nested.SomeDate = someDate; SUT.AddOne(document); // Act var result = await SUT.ProjectOneAsync( x => x.Id.Equals(document.Id), x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.True(null != result, GetTestName()); Assert.True(someContent == result.SomeContent, GetTestName()); Assert.True(someDate.Minute == result.SomeDate.Minute, GetTestName()); Assert.True(someDate.Second == result.SomeDate.Second, GetTestName()); } [Fact] public void ProjectOne() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var document = CreateTestDocument(); document.SomeContent = someContent; document.Nested.SomeDate = someDate; SUT.AddOne(document); // Act var result = SUT.ProjectOne( x => x.Id.Equals(document.Id), x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.True(null != result, GetTestName()); Assert.True(someContent == result.SomeContent, GetTestName()); Assert.True(someDate.Minute == result.SomeDate.Minute, GetTestName()); Assert.True(someDate.Second == result.SomeDate.Second, GetTestName()); } [Fact] public async Task ProjectManyAsync() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var documents = CreateTestDocuments(5); documents.ForEach(e => { e.SomeContent = someContent; e.Nested.SomeDate = someDate; }); SUT.AddMany(documents); // Act var result = await SUT.ProjectManyAsync( x => x.SomeContent == someContent, x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); Assert.True(someContent == result.First().SomeContent, GetTestName()); Assert.True(someDate.Minute == result.First().SomeDate.Minute, GetTestName()); Assert.True(someDate.Second == result.First().SomeDate.Second, GetTestName()); } [Fact] public void ProjectMany() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var documents = CreateTestDocuments(5); documents.ForEach(e => { e.SomeContent = someContent; e.Nested.SomeDate = someDate; }); SUT.AddMany(documents); // Act var result = SUT.ProjectMany( x => x.SomeContent == someContent, x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.True(5 == result.Count, GetTestName()); Assert.True(someContent == result.First().SomeContent, GetTestName()); Assert.True(someDate.Minute == result.First().SomeDate.Minute, GetTestName()); Assert.True(someDate.Second == result.First().SomeDate.Second, GetTestName()); } #endregion Project #region Max / Min Queries [Fact] public async Task GetByMaxAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First(); // Act var result = await SUT.GetByMaxAsync(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.NotNull(result); Assert.Equal(expectedMax.Id, result.Id); } [Fact] public void GetByMax() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First(); // Act var result = SUT.GetByMax(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.NotNull(result); Assert.Equal(expectedMax.Id, result.Id); } [Fact] public void GetMaxValue() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First(); // Act var result = SUT.GetMaxValue(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.False(result == default(DateTime)); Assert.Equal(expectedMax.Nested.SomeDate.Date, result.Date); } [Fact] public async Task GetMaxValueAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First(); // Act var result = await SUT.GetMaxValueAsync(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.False(result == default(DateTime)); Assert.Equal(expectedMax.Nested.SomeDate.Date, result.Date); } [Fact] public async Task GetByMinAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First(); // Act var result = await SUT.GetByMinAsync(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.NotNull(result); Assert.Equal(expectedMin.Id, result.Id); } [Fact] public void GetByMin() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First(); // Act var result = SUT.GetByMin(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.NotNull(result); Assert.Equal(expectedMin.Id, result.Id); } [Fact] public void GetMinValue() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First(); // Act var result = SUT.GetMinValue(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.True(result != default(DateTime)); Assert.Equal(expectedMin.Nested.SomeDate.Date, result.Date); } [Fact] public async Task GetMinValueAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First(); // Act var result = await SUT.GetMinValueAsync(e => e.SomeContent == criteria, e => e.Nested.SomeDate, PartitionKey); // Assert Assert.True(result != default(DateTime)); Assert.Equal(expectedMin.Nested.SomeDate.Date, result.Date); } #endregion Max / Min Queries #region Index Management static readonly SemaphoreSlim textIndexSemaphore = new SemaphoreSlim(1, 1); [Fact] public async Task CreateTextIndexNoOptionAsync() { // Arrange const string expectedIndexName = "SomeContent_text"; // Act await textIndexSemaphore.WaitAsync(); try { var result = await SUT.CreateTextIndexAsync(x => x.SomeContent, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } finally { textIndexSemaphore.Release(); } } [Fact] public async Task CreateTextIndexWithOptionAsync() { // Arrange string expectedIndexName = $"{Guid.NewGuid()}"; var option = new IndexCreationOptions { Name = expectedIndexName }; await textIndexSemaphore.WaitAsync(); try { // Act var result = await SUT.CreateTextIndexAsync(x => x.Version, option, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } finally { textIndexSemaphore.Release(); } } [Fact] public async Task CreateAscendingIndexAsync() { // Arrange const string expectedIndexName = "SomeContent_1"; // Act var result = await SUT.CreateAscendingIndexAsync(x => x.SomeContent, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } [Fact] public async Task CreateDescendingIndexAsync() { // Arrange const string expectedIndexName = "SomeContent_-1"; // Act var result = await SUT.CreateDescendingIndexAsync(x => x.SomeContent, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } [Fact] public async Task CreateHashedIndexAsync() { // Arrange const string expectedIndexName = "SomeContent_hashed"; // Act var result = await SUT.CreateHashedIndexAsync(x => x.SomeContent, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } [Fact] public async Task CreateCombinedTextIndexAsync() { // Arrange const string expectedIndexName = "SomeContent4_text_SomeContent5_text"; // Act Expression> ex = x => x.SomeContent4; Expression> ex2 = x => x.SomeContent5; var result = await SUT.CreateCombinedTextIndexAsync(new[] { ex, ex2 }, null, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); } #endregion Index Management #region Math [Fact] public async Task SumByDecimalAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.Nested.SomeAmount = 5m; e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedSum = documents.Sum(e => e.Nested.SomeAmount); // Act var result = await SUT.SumByAsync(e => e.SomeContent == criteria, e => e.Nested.SomeAmount, PartitionKey); // Assert Assert.Equal(expectedSum, result); } [Fact] public void SumByDecimal() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}.{Guid.NewGuid()}"; var documents = CreateTestDocuments(5); var i = 1; documents.ForEach(e => { e.Nested.SomeDate = e.Nested.SomeDate.AddDays(i++); e.Nested.SomeAmount = 5m; e.SomeContent = criteria; }); SUT.AddMany(documents); var expectedSum = documents.Sum(e => e.Nested.SomeAmount); // Act var result = SUT.SumBy(e => e.SomeContent == criteria, e => e.Nested.SomeAmount, PartitionKey); // Assert Assert.Equal(expectedSum, result); } #endregion Math #region Group By [Fact] public void GroupByTProjection() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); for (var i = 0; i < documents.Count - 2; i++) { documents[i].GroupingKey = 1; documents[i].SomeContent = $"{content}-{i}"; } for (var i = 3; i < documents.Count; i++) { documents[i].GroupingKey = 2; documents[i].SomeContent = $"{content}-{i}"; } SUT.AddMany(documents); // Act var result = SUT.GroupBy( e => e.GroupingKey, g => new ProjectedGroup { Key = g.Key, Content = g.Select(doc => doc.SomeContent).ToList() }, PartitionKey); // Assert var key1Group = result.First(e => e.Key == 1); Assert.NotNull(key1Group); Assert.Equal(3, key1Group.Content.Count); var key2Group = result.First(e => e.Key == 2); Assert.NotNull(key2Group); Assert.Equal(2, key2Group.Content.Count); } [Fact] public void FilteredGroupByTProjection() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); for (var i = 0; i < documents.Count - 2; i++) { documents[i].GroupingKey = 4; documents[i].SomeContent = $"{content}-{i}"; } for (var i = 3; i < documents.Count; i++) { documents[i].GroupingKey = 5; documents[i].SomeContent = $"{content}-{i}"; } var guid1 = Guid.NewGuid().ToString("n"); var guid2 = Guid.NewGuid().ToString("n"); for (var i = 0; i < documents.Count - 1; i++) { documents[i].Children = new List { new Child(guid1, guid2) }; } SUT.AddMany(documents); // Act var result = SUT.GroupBy( e => e.Children.Any(c => c.Type == guid1), e => e.GroupingKey, g => new ProjectedGroup { Key = g.Key, Content = g.Select(doc => doc.SomeContent).ToList() }, PartitionKey); // Assert var key1Group = result.First(e => e.Key == 4); Assert.NotNull(key1Group); Assert.Equal(3, key1Group.Content.Count); var key2Group = result.First(e => e.Key == 5); Assert.NotNull(key2Group); Assert.Single(key2Group.Content); } #endregion Group By #region Pagination public static Random Random = new Random(); [Fact] public async Task GetSortedPaginatedAsync() { // Arrange var content = $"{Guid.NewGuid()}"; var documents = CreateTestDocuments(10); for (var i = 0; i < 5; i++) { documents[i].GroupingKey = 8; documents[i].Nested.SomeAmount = Random.Next(1, 500000); documents[i].SomeContent = content; } for (var i = 5; i < documents.Count; i++) { documents[i].GroupingKey = 9; documents[i].SomeContent = content; } SUT.AddMany(documents); documents = documents.OrderByDescending(e => e.Nested.SomeAmount).ToList(); var notExpected = documents.First(); var expectedFirstResult = documents[1]; // Act var result = await SUT.GetSortedPaginatedAsync( e => e.GroupingKey == 8 && e.SomeContent == content, e => e.Nested.SomeAmount, false, 1,5, PartitionKey); // Assert Assert.Equal(4, result.Count); Assert.True(!result.Contains(notExpected)); Assert.Equal(expectedFirstResult.Id, result[0].Id); } [Fact] public async Task GetSortedPaginatedAsyncWithSortOptions() { // Arrange var content = $"{Guid.NewGuid()}"; var documents = CreateTestDocuments(10); for (var i = 0; i < 5; i++) { documents[i].GroupingKey = 8; documents[i].Nested.SomeAmount = Random.Next(1, 500000); documents[i].SomeContent = content; } for (var i = 5; i < documents.Count; i++) { documents[i].GroupingKey = 9; documents[i].SomeContent = content; } SUT.AddMany(documents); documents = documents.OrderByDescending(e => e.Nested.SomeAmount).ToList(); var notExpected = documents.First(); var expectedFirstResult = documents[1]; var sorting = Builders.Sort.Descending(e => e.Nested.SomeAmount); // Act var result = await SUT.GetSortedPaginatedAsync( e => e.GroupingKey == 8 && e.SomeContent == content, sorting, 1, 5, PartitionKey); // Assert Assert.Equal(4, result.Count); Assert.True(!result.Contains(notExpected)); Assert.Equal(expectedFirstResult.Id, result[0].Id); } #endregion Pagination #region Test Utils [MethodImpl(MethodImplOptions.NoInlining)] private string GetCurrentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(1); return sf.GetMethod().Name; } [MethodImpl(MethodImplOptions.NoInlining)] private string GetParentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(2); var method = sf.GetMethod().DeclaringType.Name; return method; } private string GetTestName() { return $"{TestClassName}{PartitionKey}.{GetParentMethod()}"; } private string GetContent() { return $"{TestClassName}{PartitionKey}.{Guid.NewGuid()}.{GetParentMethod()}"; } private void Cleanup() { // We drop the collection at the end of each test session. if (!string.IsNullOrEmpty(PartitionKey)) { SUT.DropTestCollection(PartitionKey); } else { SUT.DropTestCollection(); } } #endregion Test Utils } } ================================================ FILE: CoreIntegrationTests/Infrastructure/MongoDbTKeyDocumentTestBase.Update.cs ================================================ using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace CoreIntegrationTests.Infrastructure { public abstract partial class MongoDbTKeyDocumentTestBase : IClassFixture> where T : TestDoc, new() where TKey : IEquatable { #region Update One [Fact] public void UpdateOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); document.SomeContent = content; // Act var result = SUT.UpdateOne(document); // Assert Assert.True(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public async Task UpdateOneAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); document.SomeContent = content; // Act var result = await SUT.UpdateOneAsync(document); // Assert Assert.True(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public void UpdateOneField() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = SUT.UpdateOne(document, x => x.SomeContent, content); // Assert Assert.True(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public async Task UpdateOneFieldAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = await SUT.UpdateOneAsync(document, x => x.SomeContent, content); // Assert Assert.True(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public void UpdateOneFieldWithFilter() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = SUT.UpdateOne(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public async Task UpdateOneFieldWithFilterAsync() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = await SUT.UpdateOneAsync(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument, GetTestName()); Assert.True(content == updatedDocument.SomeContent, GetTestName()); } [Fact] public async Task UpdateOneAsyncWithUpdateDefinition() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = MongoDB.Driver.Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); // Act var result = await SUT.UpdateOneAsync(document, updateDef); // Assert Assert.True(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument); Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); } [Fact] public void UpdateOneWithUpdateDefinition() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = MongoDB.Driver.Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); // Act var result = SUT.UpdateOne(document, updateDef); // Assert Assert.True(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.True(null != updatedDocument); Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); } #endregion Update One #region Update Many [Fact] public async Task UpdateManyWithLinqFilterAsync() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var content = GetContent(); // Act var result = await SUT.UpdateManyAsync(x => docIds.Contains(x.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocument = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocument.Count == 2); Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName()); } [Fact] public async Task UpdateManyWithFilterDefinitionAsync() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var filterDefinition = Builders.Filter.Where(x => docIds.Contains(x.Id)); var content = GetContent(); // Act var result = await SUT.UpdateManyAsync(filterDefinition, x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocument = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocument.Count == 2); Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName()); } [Fact] public async Task UpdateManyWithLinqFilterAndUpdateDefinitionAsync() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); var content = GetContent(); // Act var result = await SUT.UpdateManyAsync(x => docIds.Contains(x.Id), updateDef, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocuments = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocuments.Count == 2); updatedDocuments.ForEach(updatedDocument => { Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); }); } [Fact] public async Task UpdateManyWithFilterAndUpdateDefinitionsAsync() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); var docIds = documents.Select(u => u.Id).ToArray(); var filterDefinition = Builders.Filter.Where(x => docIds.Contains(x.Id)); var content = GetContent(); // Act var result = await SUT.UpdateManyAsync(filterDefinition, updateDef, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocuments = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocuments.Count == 2); updatedDocuments.ForEach(updatedDocument => { Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); }); } [Fact] public void UpdateManyWithLinqFilter() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var content = GetContent(); // Act var result = SUT.UpdateMany(x => docIds.Contains(x.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocument = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocument.Count == 2); Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName()); } [Fact] public void UpdateManyWithFilterDefinition() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var filterDefinition = Builders.Filter.Where(x => docIds.Contains(x.Id)); var content = GetContent(); // Act var result = SUT.UpdateMany(filterDefinition, x => x.SomeContent, content, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocument = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocument.Count == 2); Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName()); } [Fact] public void UpdateManyWithLinqFilterAndUpdateDefinition() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var docIds = documents.Select(u => u.Id).ToArray(); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); var content = GetContent(); // Act var result = SUT.UpdateMany(x => docIds.Contains(x.Id), updateDef, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocuments = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocuments.Count == 2); updatedDocuments.ForEach(updatedDocument => { Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); }); } [Fact] public void UpdateManyWithFilterAndUpdateDefinitions() { // Arrange var documents = CreateTestDocuments(2); SUT.AddMany(documents); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); var docIds = documents.Select(u => u.Id).ToArray(); var filterDefinition = Builders.Filter.Where(x => docIds.Contains(x.Id)); var content = GetContent(); // Act var result = SUT.UpdateMany(filterDefinition, updateDef, PartitionKey); // Assert Assert.True(result == 2, GetTestName()); var updatedDocuments = SUT.GetAll(x => docIds.Contains(x.Id), PartitionKey); Assert.True(updatedDocuments.Count == 2); updatedDocuments.ForEach(updatedDocument => { Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName()); Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName()); Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName()); Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName()); }); } #endregion Update Many } } ================================================ FILE: CoreIntegrationTests/Infrastructure/MongoDbTestFixture.cs ================================================ using MongoDbGenericRepository; using MongoDbGenericRepository.Models; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace CoreIntegrationTests.Infrastructure { public class MongoDbTestFixture : IDisposable where T : IDocument, new() where TKey : IEquatable { public IMongoDbContext Context; public MongoDbTestFixture() { } public string PartitionKey { get; set; } public static ConcurrentBag DocsToDelete { get; set; } = new ConcurrentBag(); public virtual void Dispose() { if (DocsToDelete.Any()) { TestRepository.Instance.DeleteMany(DocsToDelete.ToList()); } } public T CreateTestDocument() { var doc = new T(); DocsToDelete.Add(doc); return doc; } public List CreateTestDocuments(int numberOfDocumentsToCreate) { var docs = new List(); for (var i = 0; i < numberOfDocumentsToCreate; i++) { var doc = new T(); docs.Add(doc); DocsToDelete.Add(doc); } return docs; } } } ================================================ FILE: CoreIntegrationTests/Infrastructure/RandomExtensions.cs ================================================ using System; namespace CoreIntegrationTests.Infrastructure { // Thanks BlueRaja - Danny Pflughoeft https://stackoverflow.com/a/13095144/5103354 /// /// Extensions for the random number generator /// public static class RandomExtensions { /// /// Returns a random long from min (inclusive) to max (exclusive) /// /// The given random instance /// The inclusive minimum bound /// The exclusive maximum bound. Must be greater than min public static long NextLong(this Random random, long min, long max) { if (max <= min) throw new ArgumentOutOfRangeException("max", "max must be > min!"); //Working with ulong so that modulo works correctly with values > long.MaxValue ulong uRange = (ulong)(max - min); //Prevent a modulo bias; see https://stackoverflow.com/a/10984975/238419 //for more information. //In the worst case, the expected number of calls is 2 (though usually it's //much closer to 1) so this loop doesn't really hurt performance at all. ulong ulongRand; do { byte[] buf = new byte[8]; random.NextBytes(buf); ulongRand = (ulong)BitConverter.ToInt64(buf, 0); } while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange); return (long)(ulongRand % uRange) + min; } /// /// Returns a random long from 0 (inclusive) to max (exclusive) /// /// The given random instance /// The exclusive maximum bound. Must be greater than 0 public static long NextLong(this Random random, long max) { return random.NextLong(0, max); } /// /// Returns a random long over all possible values of long (except long.MaxValue, similar to /// random.Next()) /// /// The given random instance public static long NextLong(this Random random) { return random.NextLong(long.MinValue, long.MaxValue); } } } ================================================ FILE: CoreIntegrationTests/Infrastructure/TestClasses.cs ================================================ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDbGenericRepository.Models; using MongoDbGenericRepository.Utils; using System; using System.Collections.Generic; namespace CoreIntegrationTests.Infrastructure { public class ProjectedGroup { public int Key { get; set; } public List Content { get; set; } } public class MyTestProjection { public string SomeContent { get; set; } public DateTime SomeDate { get; set; } } public class Nested { public DateTime SomeDate { get; set; } [BsonRepresentation(BsonType.Decimal128)] public decimal SomeAmount { get; set; } } public class Child { public Child(string type, string value) { Type = type; Value = value; } public string Type { get; set; } public string Value { get; set; } } public class TestDoc : Document { public TestDoc() { Version = 2; Nested = new Nested { SomeDate = DateTime.UtcNow }; Children = new List(); } public int SomeValue { get; set; } public string SomeContent { get; set; } public string SomeContent2 { get; set; } public string SomeContent3 { get; set; } public int GroupingKey { get; set; } public Nested Nested { get; set; } public List Children { get; set; } } public class TestDoc : IDocument where TKey : IEquatable { [BsonId] public TKey Id { get; set; } public int Version { get; set; } public TestDoc() { InitializeFields(); Version = 2; Nested = new Nested { SomeDate = DateTime.UtcNow }; Children = new List(); } public int GroupingKey { get; set; } public string SomeContent { get; set; } public string SomeContent4 { get; set; } public string SomeContent5 { get; set; } public Nested Nested { get; set; } public List Children { get; set; } public TId Init() { return IdGenerator.GetId(); } private void InitializeFields() { Id = Init(); } } } ================================================ FILE: CoreIntegrationTests/Infrastructure/TestRepository.cs ================================================ using MongoDB.Bson; using MongoDbGenericRepository; using System; namespace CoreIntegrationTests.Infrastructure { public interface ITestRepository : IBaseMongoRepository where TKey : IEquatable { void DropTestCollection(); void DropTestCollection(string partitionKey); } public class TestTKeyRepository : BaseMongoRepository, ITestRepository where TKey : IEquatable { const string connectionString = "mongodb://localhost:27017/MongoDbTests"; private static readonly ITestRepository _instance = new TestTKeyRepository(connectionString); /// private TestTKeyRepository(string connectionString) : base(connectionString) { } public static ITestRepository Instance { get { return _instance; } } public void DropTestCollection() { MongoDbContext.DropCollection(); } public void DropTestCollection(string partitionKey) { MongoDbContext.DropCollection(partitionKey); } } /// /// A singleton implementation of the TestRepository /// public sealed class TestRepository : BaseMongoRepository, ITestRepository { const string connectionString = "mongodb://localhost:27017"; private static readonly ITestRepository _instance = new TestRepository(connectionString, "MongoDbTests"); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static TestRepository() { } /// private TestRepository(string connectionString, string databaseName) : base(connectionString, databaseName) { } public static ITestRepository Instance { get { return _instance; } } public void DropTestCollection() { MongoDbContext.DropCollection(); } public void DropTestCollection(string partitionKey) { MongoDbContext.DropCollection(partitionKey); } } } ================================================ FILE: CoreUnitTests/.editorconfig ================================================ # All Files [*] charset = utf-8 indent_style = space indent_size = 4 insert_final_newline = true trim_trailing_whitespace = true ######################################### # File Extension Settings ########################################## # .NET Style Rules # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#net-style-rules [*.cs] # "this." and "Me." qualifiers dotnet_style_qualification_for_field = false:warning dotnet_style_qualification_for_property = false:warning dotnet_style_qualification_for_method = false:warning dotnet_style_qualification_for_event = false:warning # Language keywords instead of framework type names for type references dotnet_style_predefined_type_for_locals_parameters_members = true:warning dotnet_style_predefined_type_for_member_access = true:warning # Modifier preferences dotnet_style_require_accessibility_modifiers = always:warning csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:warning visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:warning dotnet_style_readonly_field = true:warning # Parentheses preferences dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning dotnet_style_parentheses_in_other_operators = never_if_unnecessary:warning # Expression-level preferences dotnet_style_object_initializer = true:warning dotnet_style_collection_initializer = true:warning dotnet_style_explicit_tuple_names = true:warning dotnet_style_prefer_inferred_tuple_names = true:warning dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning dotnet_style_prefer_auto_properties = true:warning dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion dotnet_diagnostic.IDE0045.severity = suggestion dotnet_style_prefer_conditional_expression_over_return = false:suggestion dotnet_diagnostic.IDE0046.severity = suggestion dotnet_style_prefer_compound_assignment = true:warning dotnet_style_prefer_simplified_interpolation = true:warning dotnet_style_prefer_simplified_boolean_expressions = true:warning # Null-checking preferences dotnet_style_coalesce_expression = true:warning dotnet_style_null_propagation = true:warning dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning # File header preferences # file_header_template = \n© PROJECT-AUTHOR\n # If you use StyleCop, you'll need to disable SA1636: File header copyright text should match. # dotnet_diagnostic.SA1636.severity = none # Undocumented dotnet_style_operator_placement_when_wrapping = end_of_line:warning csharp_style_prefer_null_check_over_type_check = true:warning dotnet_analyzer_diagnostic.severity = warning dotnet_code_quality_unused_parameters = all:warning dotnet_remove_unnecessary_suppression_exclusions = none:warning dotnet_sort_system_directives_first = true dotnet_separate_import_directive_groups = false dotnet_style_namespace_match_folder = true:suggestion dotnet_diagnostic.IDE0130.severity = suggestion dotnet_naming_style.camel_case_style.capitalization = camel_case dotnet_naming_style.pascal_case_style.capitalization = pascal_case dotnet_naming_style.first_upper_style.capitalization = first_word_upper dotnet_naming_style.prefix_interface_with_i_style.capitalization = pascal_case dotnet_naming_style.prefix_interface_with_i_style.required_prefix = I dotnet_naming_style.prefix_type_parameters_with_t_style.capitalization = pascal_case dotnet_naming_style.prefix_type_parameters_with_t_style.required_prefix = T dotnet_naming_style.disallowed_style.capitalization = pascal_case dotnet_naming_style.disallowed_style.required_prefix = ____RULE_VIOLATION____ dotnet_naming_style.disallowed_style.required_suffix = ____RULE_VIOLATION____ dotnet_naming_style.internal_error_style.capitalization = pascal_case dotnet_naming_style.internal_error_style.required_prefix = ____INTERNAL_ERROR____ dotnet_naming_style.internal_error_style.required_suffix = ____INTERNAL_ERROR____ dotnet_naming_symbols.public_protected_constant_fields_group.applicable_accessibilities = public, protected, protected_internal dotnet_naming_symbols.public_protected_constant_fields_group.required_modifiers = const dotnet_naming_symbols.public_protected_constant_fields_group.applicable_kinds = field dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.symbols = public_protected_constant_fields_group dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.style = pascal_case_style dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.severity = warning dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_accessibilities = public, protected, protected_internal dotnet_naming_symbols.public_protected_static_readonly_fields_group.required_modifiers = static, readonly dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_kinds = field dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.symbols = public_protected_static_readonly_fields_group dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.severity = warning dotnet_naming_symbols.other_public_protected_fields_group.applicable_accessibilities = public, protected, protected_internal dotnet_naming_symbols.other_public_protected_fields_group.applicable_kinds = field dotnet_naming_rule.other_public_protected_fields_disallowed_rule.symbols = other_public_protected_fields_group dotnet_naming_rule.other_public_protected_fields_disallowed_rule.style = disallowed_style dotnet_naming_rule.other_public_protected_fields_disallowed_rule.severity = error dotnet_naming_symbols.stylecop_constant_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private dotnet_naming_symbols.stylecop_constant_fields_group.required_modifiers = const dotnet_naming_symbols.stylecop_constant_fields_group.applicable_kinds = field dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.symbols = stylecop_constant_fields_group dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.style = pascal_case_style dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.severity = warning dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private dotnet_naming_symbols.stylecop_static_readonly_fields_group.required_modifiers = static, readonly dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_kinds = field dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.symbols = stylecop_static_readonly_fields_group dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.severity = warning dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_kinds = field dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.symbols = stylecop_fields_must_be_private_group dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.style = disallowed_style dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.severity = error dotnet_naming_symbols.stylecop_private_fields_group.applicable_accessibilities = private dotnet_naming_symbols.stylecop_private_fields_group.applicable_kinds = field dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.symbols = stylecop_private_fields_group dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.style = camel_case_style dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.severity = warning dotnet_naming_symbols.stylecop_local_fields_group.applicable_accessibilities = local dotnet_naming_symbols.stylecop_local_fields_group.applicable_kinds = local dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.symbols = stylecop_local_fields_group dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.style = camel_case_style dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.severity = silent dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_accessibilities = * dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_kinds = field dotnet_naming_rule.sanity_check_uncovered_field_case_rule.symbols = sanity_check_uncovered_field_case_group dotnet_naming_rule.sanity_check_uncovered_field_case_rule.style = internal_error_style dotnet_naming_rule.sanity_check_uncovered_field_case_rule.severity = error dotnet_naming_symbols.element_group.applicable_kinds = namespace, class, enum, struct, delegate, event, method, property dotnet_naming_rule.element_rule.symbols = element_group dotnet_naming_rule.element_rule.style = pascal_case_style dotnet_naming_rule.element_rule.severity = warning dotnet_naming_symbols.interface_group.applicable_kinds = interface dotnet_naming_rule.interface_rule.symbols = interface_group dotnet_naming_rule.interface_rule.style = prefix_interface_with_i_style dotnet_naming_rule.interface_rule.severity = warning dotnet_naming_symbols.type_parameter_group.applicable_kinds = type_parameter dotnet_naming_rule.type_parameter_rule.symbols = type_parameter_group dotnet_naming_rule.type_parameter_rule.style = prefix_type_parameters_with_t_style dotnet_naming_rule.type_parameter_rule.severity = warning dotnet_naming_symbols.parameters_group.applicable_kinds = parameter dotnet_naming_rule.parameters_rule.symbols = parameters_group dotnet_naming_rule.parameters_rule.style = camel_case_style dotnet_naming_rule.parameters_rule.severity = warning csharp_style_var_for_built_in_types = true:warning csharp_style_var_when_type_is_apparent = true:warning csharp_style_var_elsewhere = true:warning csharp_style_expression_bodied_methods = true:warning csharp_style_expression_bodied_constructors = true:warning csharp_style_expression_bodied_operators = true:warning csharp_style_expression_bodied_properties = true:warning csharp_style_expression_bodied_indexers = true:warning csharp_style_expression_bodied_accessors = true:warning csharp_style_expression_bodied_lambdas = true:warning csharp_style_expression_bodied_local_functions = true:warning csharp_style_pattern_matching_over_is_with_cast_check = true:warning csharp_style_pattern_matching_over_as_with_null_check = true:warning csharp_style_prefer_switch_expression = true:warning csharp_style_prefer_pattern_matching = true:warning csharp_style_prefer_not_pattern = true:warning csharp_style_inlined_variable_declaration = true:warning csharp_prefer_simple_default_expression = true:warning csharp_style_pattern_local_over_anonymous_function = true:warning csharp_style_deconstructed_variable_declaration = true:warning csharp_style_prefer_index_operator = true:warning csharp_style_prefer_range_operator = true:warning csharp_style_implicit_object_creation_when_type_is_apparent = true:warning csharp_style_throw_expression = true:warning csharp_style_conditional_delegate_call = true:warning csharp_prefer_braces = true:warning csharp_prefer_simple_using_statement = true:suggestion dotnet_diagnostic.IDE0063.severity = suggestion csharp_using_directive_placement = outside_namespace csharp_prefer_static_local_function = true:warning csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion dotnet_diagnostic.IDE0058.severity = suggestion csharp_style_unused_value_assignment_preference = discard_variable:suggestion dotnet_diagnostic.IDE0059.severity = suggestion csharp_new_line_before_open_brace = all csharp_new_line_before_else = true csharp_new_line_before_catch = true csharp_new_line_before_finally = true csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_between_query_expression_clauses = true csharp_indent_case_contents = true csharp_indent_switch_labels = true csharp_indent_labels = no_change csharp_indent_block_contents = true csharp_indent_braces = false csharp_indent_case_contents_when_block = false csharp_space_after_cast = false csharp_space_after_keywords_in_control_flow_statements = true csharp_space_between_parentheses = false csharp_space_before_colon_in_inheritance_clause = true csharp_space_after_colon_in_inheritance_clause = true csharp_space_around_binary_operators = before_and_after csharp_space_between_method_declaration_parameter_list_parentheses = false csharp_space_between_method_declaration_empty_parameter_list_parentheses = false csharp_space_between_method_declaration_name_and_open_parenthesis = false csharp_space_between_method_call_parameter_list_parentheses = false csharp_space_between_method_call_empty_parameter_list_parentheses = false csharp_space_between_method_call_name_and_opening_parenthesis = false csharp_space_after_comma = true csharp_space_before_comma = false csharp_space_after_dot = false csharp_space_before_dot = false csharp_space_after_semicolon_in_for_statement = true csharp_space_before_semicolon_in_for_statement = false csharp_space_around_declaration_statements = false csharp_space_before_open_square_brackets = false csharp_space_between_empty_square_brackets = false csharp_space_between_square_brackets = false csharp_preserve_single_line_statements = false csharp_preserve_single_line_blocks = true csharp_style_namespace_declarations = file_scoped:warning dotnet_diagnostic.CA1707.severity = none ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/AddTests/AddManyAsyncTests.cs ================================================ using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.AddTests; public class AddManyAsyncTests : TestMongoRepositoryContext { [Fact] public async Task WithDocument_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany().ToList(); Creator = new Mock(); // Act await Sut.AddManyAsync(documents); // Assert Creator.Verify(x => x.AddManyAsync(documents, CancellationToken.None), Times.Once); } [Fact] public async Task WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Creator = new Mock(); // Act await Sut.AddManyAsync(documents, token); // Assert Creator.Verify(x => x.AddManyAsync(documents, token), Times.Once); } #region Keyed [Fact] public async Task Keyed_WithDocument_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany>().ToList(); Creator = new Mock(); // Act await Sut.AddManyAsync, int>(documents); // Assert Creator.Verify(x => x.AddManyAsync, int>(documents, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); Creator = new Mock(); // Act await Sut.AddManyAsync, int>(documents, token); // Assert Creator.Verify(x => x.AddManyAsync, int>(documents, token), Times.Once); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/AddTests/AddManyTests.cs ================================================ using System; using System.Linq; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.AddTests; public class AddManyTests : TestMongoRepositoryContext { [Fact] public void WithDocument_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany().ToList(); Creator = new Mock(); // Act Sut.AddMany(documents); // Assert Creator.Verify(x => x.AddMany(documents, CancellationToken.None), Times.Once); } [Fact] public void WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Creator = new Mock(); // Act Sut.AddMany(documents, token); // Assert Creator.Verify(x => x.AddMany(documents, token), Times.Once); } #region Keyed [Fact] public void Keyed_WithDocument_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany>().ToList(); Creator = new Mock(); // Act Sut.AddMany, int>(documents); // Assert Creator.Verify(x => x.AddMany, int>(documents, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); Creator = new Mock(); // Act Sut.AddMany, int>(documents, token); // Assert Creator.Verify(x => x.AddMany, int>(documents, token), Times.Once); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/AddTests/AddOneAsyncTests.cs ================================================ using System; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.AddTests; public class AddOneAsyncTests : TestMongoRepositoryContext { [Fact] public async Task WithDocument_ShouldAddOne() { // Arrange var document = Fixture.Create(); Creator = new Mock(); // Act await Sut.AddOneAsync(document); // Assert Creator.Verify(x => x.AddOneAsync(document, CancellationToken.None), Times.Once); } [Fact] public async Task WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); Creator = new Mock(); // Act await Sut.AddOneAsync(document, token); // Assert Creator.Verify(x => x.AddOneAsync(document, token), Times.Once); } #region Keyed [Fact] public async Task Keyed_WithDocument_ShouldAddOne() { // Arrange var document = Fixture.Create>(); Creator = new Mock(); // Act await Sut.AddOneAsync, int>(document); // Assert Creator.Verify(x => x.AddOneAsync, int>(document, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Creator = new Mock(); // Act await Sut.AddOneAsync, int>(document, token); // Assert Creator.Verify(x => x.AddOneAsync, int>(document, token), Times.Once); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/AddTests/AddOneTests.cs ================================================ using System; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.AddTests; public class AddOneTests : TestMongoRepositoryContext { [Fact] public void WithDocument_ShouldAddOne() { // Arrange var document = Fixture.Create(); Creator = new Mock(); // Act Sut.AddOne(document); // Assert Creator.Verify(x => x.AddOne(document, CancellationToken.None), Times.Once); } [Fact] public void WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); Creator = new Mock(); // Act Sut.AddOne(document, token); // Assert Creator.Verify(x => x.AddOne(document, token), Times.Once); } #region Keyed [Fact] public void Keyed_WithDocument_ShouldAddOne() { // Arrange var document = Fixture.Create>(); Creator = new Mock(); // Act Sut.AddOne, int>(document); // Assert Creator.Verify(x => x.AddOne, int>(document, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Creator = new Mock(); // Act Sut.AddOne, int>(document, token); // Assert Creator.Verify(x => x.AddOne, int>(document, token), Times.Once); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/DeleteTests/DeleteManyAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.DeleteTests; public class DeleteManyAsyncTests : TestMongoRepositoryContext { [Fact] public async Task WithDocuments_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany().ToList(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync(It.IsAny>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(documents); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync(documents, CancellationToken.None), Times.Once); } [Fact] public async Task WithDocumentsAndCancellationToken_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany().ToList(); var count = Fixture.Create(); var cancellationToken = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync(It.IsAny>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(documents, cancellationToken); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync(documents, cancellationToken), Times.Once); } [Fact] public async Task WithFilter_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync( It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync( It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync(filter, null, token), Times.Once); } [Fact] public async Task WithFilterAndPartitionKey_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync( It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync( It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync(filter, partitionKey, token), Times.Once); } #region Keyed [Fact] public async Task Keyed_WithDocuments_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany>().ToList(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>(It.IsAny>>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync, int>(documents); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(documents, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithDocumentsAndCancellationToken_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany>().ToList(); var count = Fixture.Create(); var cancellationToken = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>(It.IsAny>>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync, int>(documents, cancellationToken); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(documents, cancellationToken), Times.Once); } [Fact] public async Task Keyed_WithFilter_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync, int>(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync, int>(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(filter, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKey_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync, int>(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync, int>(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(filter, partitionKey, token), Times.Once); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/DeleteTests/DeleteManyTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.DeleteTests; public class DeleteManyTests : TestMongoRepositoryContext { [Fact] public void WithDocuments_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany().ToList(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany(It.IsAny>(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany(documents); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany(documents, CancellationToken.None), Times.Once); } [Fact] public void WithDocumentsAndCancellationToken_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany().ToList(); var count = Fixture.Create(); var token = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany(It.IsAny>(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany(documents, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany(documents, token), Times.Once); } [Fact] public void WithFilter_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany(It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany(filter, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany(It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany(filter, null, token), Times.Once); } [Fact] public void WithFilterAndPartitionKey_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany(It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany(It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany(filter, partitionKey, token), Times.Once); } #region Keyed [Fact] public void Keyed_WithDocuments_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany>().ToList(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>(It.IsAny>>(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany, int>(documents); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(documents, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithDocumentsAndCancellationToken_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany>().ToList(); var count = Fixture.Create(); var token = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>(It.IsAny>>(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany, int>(documents, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(documents, token), Times.Once); } [Fact] public void Keyed_WithFilter_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>(It.IsAny, bool>>>(), null, CancellationToken.None)) .Returns(count); // Act var result = Sut.DeleteMany, int>(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany, int>(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(filter, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKey_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany, int>(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany, int>(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(filter, partitionKey, token), Times.Once); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/DeleteTests/DeleteOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.DeleteTests; public class DeleteOneAsyncTests : TestMongoRepositoryContext { [Fact] public async Task WithDocument_ShouldDeleteOne() { // Arrange var document = Fixture.Create(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(document); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync(document, CancellationToken.None), Times.Once); } [Fact] public async Task WithDocumentAndCancellationToken_ShouldDeleteOne() { // Arrange var document = Fixture.Create(); var count = Fixture.Create(); var token = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(document, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync(document, token), Times.Once); } [Fact] public async Task WithFilter_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync(It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync(It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync(filter, null, token), Times.Once); } [Fact] public async Task WithFilterAndPartitionKey_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync(It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync(It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync(filter, partitionKey, token), Times.Once); } #region Keyed [Fact] public async Task Keyed_WithDocument_ShouldDeleteOne() { // Arrange var document = Fixture.Create>(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync, int>(document); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(document, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithDocumentAndCancellationToken_ShouldDeleteOne() { // Arrange var document = Fixture.Create>(); var count = Fixture.Create(); var token = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync, int>(document, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(document, token), Times.Once); } [Fact] public async Task Keyed_WithFilter_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync, int>(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync, int>(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(filter, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKey_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync, int>(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync, int>(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(filter, partitionKey, token), Times.Once); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/DeleteTests/DeleteOneTests.cs ================================================ namespace CoreUnitTests.BaseMongoRepositoryTests.DeleteTests; using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using FluentAssertions; using Infrastructure; using Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; public class DeleteOneTests : TestMongoRepositoryContext { [Fact] public void WithDocument_ShouldDeleteOne() { // Arrange var document = Fixture.Create(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne(It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(document); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne(document, CancellationToken.None), Times.Once); } [Fact] public void WithDocumentAndCancellationToken_ShouldDeleteOne() { // Arrange var document = Fixture.Create(); var count = Fixture.Create(); var token = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne(It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(document, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne(document, token), Times.Once); } [Fact] public void WithFilter_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne(It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne(filter, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup( x => x.DeleteOne( It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne(filter, null, token), Times.Once); } [Fact] public void WithFilterAndPartitionKey_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup( x => x.DeleteOne( It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup( x => x.DeleteOne( It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne(filter, partitionKey, token), Times.Once); } [Fact] public void WithKeyedDocument_ShouldDeleteOne() { // Arrange var document = Fixture.Create>(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne, int>(It.IsAny>(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne, int>(document); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(document, CancellationToken.None), Times.Once); } [Fact] public void WithKeyedDocumentAndCancellationToken_ShouldDeleteOne() { // Arrange var document = Fixture.Create>(); var count = Fixture.Create(); var token = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne, int>(It.IsAny>(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne, int>(document, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(document, token), Times.Once); } [Fact] public void Keyed_WithFilter_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup( x => x.DeleteOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne, int>(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup( x => x.DeleteOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne, int>(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(filter, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKey_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup( x => x.DeleteOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne, int>(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup( x => x.DeleteOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne, int>(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(filter, partitionKey, token), Times.Once); } } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/IndexTests/BaseIndexTests.cs ================================================ using CoreUnitTests.Infrastructure; using MongoDB.Bson; using MongoDB.Driver; using Moq; namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests; public class BaseIndexTests : TestMongoRepositoryContext { protected static Mock> SetupIndex(BsonDocument index, Mock> collection) { var asyncCursor = new Mock>(); asyncCursor .SetupSequence(x => x.MoveNextAsync(It.IsAny())) .ReturnsAsync(true) .ReturnsAsync(false); asyncCursor .SetupGet(x => x.Current) .Returns([index]); var indexManager = new Mock>(); indexManager .Setup(x => x.ListAsync(It.IsAny())) .ReturnsAsync(asyncCursor.Object); collection .SetupGet(x => x.Indexes) .Returns(indexManager.Object); return asyncCursor; } } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/IndexTests/CreateAscendingIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests; public class CreateAscendingIndexAsyncTests : BaseIndexTests { private readonly Expression, object>> keyedFieldExpression = t => t.SomeContent2; private readonly Expression> fieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(fieldExpression); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync(fieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(fieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync(fieldExpression, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(fieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync( fieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(fieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync( fieldExpression, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(fieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync( fieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(fieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync( fieldExpression, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(fieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync( fieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(fieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync( fieldExpression, options, partitionKey, token)); } #region Keyed [Fact] public async Task Keyed_WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync, int>(keyedFieldExpression); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>(keyedFieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync, int>(keyedFieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>(keyedFieldExpression, null, null, token)); } [Fact] public async Task Keyed_WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync, int>(keyedFieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync, int>(keyedFieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, options, null, token)); } [Fact] public async Task Keyed_WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync, int>(keyedFieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync, int>(keyedFieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, null, partitionKey, token)); } [Fact] public async Task Keyed_WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync, int>(keyedFieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync, int>(keyedFieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, options, partitionKey, token)); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/IndexTests/CreateCombinedTextIndexAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; using CancellationToken = System.Threading.CancellationToken; namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests; public class CreateCombinedTextIndexAsyncTests : BaseIndexTests { private readonly List>> fieldExpressions = new() {t => t.SomeContent2, t => t.SomeContent3}; private readonly List, object>>> keyedFieldExpressions = new() {t => t.SomeContent2, t => t.SomeContent3}; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(fieldExpressions); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync(fieldExpressions, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(fieldExpressions, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync(fieldExpressions, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync( fieldExpressions, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync( fieldExpressions, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(fieldExpressions, partitionKey); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync( fieldExpressions, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(fieldExpressions, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync( fieldExpressions, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync( fieldExpressions, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync( fieldExpressions, options, partitionKey, token)); } #region Keyed [Fact] public async Task Keyed_WithKeyedFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, null, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, null, null, token)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, options); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, options, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, options, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, options, null, token)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, partitionKey); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, null, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, null, partitionKey, token)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, options, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, options, partitionKey, token)); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/IndexTests/CreateDescendingIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests; public class CreateDescendingIndexAsyncTests : BaseIndexTests { private readonly Expression, object>> keyedFieldExpression = t => t.SomeContent2; private readonly Expression> fieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(fieldExpression); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync(fieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(fieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync(fieldExpression, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(fieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync( fieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(fieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync( fieldExpression, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(fieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync( fieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(fieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync( fieldExpression, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(fieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync( fieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(fieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync( fieldExpression, options, partitionKey, token)); } #region Keyed [Fact] public async Task Keyed_WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync, int>(keyedFieldExpression); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>(keyedFieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync, int>(keyedFieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>(keyedFieldExpression, null, null, token)); } [Fact] public async Task Keyed_WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync, int>(keyedFieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync, int>(keyedFieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, options, null, token)); } [Fact] public async Task Keyed_WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync, int>(keyedFieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync, int>(keyedFieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, null, partitionKey, token)); } [Fact] public async Task Keyed_WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync, int>(keyedFieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync, int>(keyedFieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, options, partitionKey, token)); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/IndexTests/CreateHashedIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; using CancellationToken = System.Threading.CancellationToken; namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests; public class CreateHashedIndexAsyncTests : BaseIndexTests { private readonly Expression> fieldExpression = t => t.SomeContent2; private readonly Expression, object>> keyedFieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(fieldExpression); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync(fieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(fieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync(fieldExpression, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(fieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync( fieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(fieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync( fieldExpression, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(fieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync( fieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(fieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync( fieldExpression, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(fieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync( fieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(fieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync( fieldExpression, options, partitionKey, token)); } #region Keyed [Fact] public async Task Keyed_WithKeyedFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync, int>(keyedFieldExpression); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>(keyedFieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync, int>(keyedFieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>(keyedFieldExpression, null, null, token)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync, int>(keyedFieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync, int>(keyedFieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, options, null, token)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync, int>(keyedFieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync, int>(keyedFieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, null, partitionKey, token)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync, int>(keyedFieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync, int>(keyedFieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, options, partitionKey, token)); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/IndexTests/CreateTextIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; using CancellationToken = System.Threading.CancellationToken; namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests; public class CreateTextIndexAsyncTests : BaseIndexTests { private readonly Expression> fieldExpression = t => t.SomeContent2; private readonly Expression, object>> keyedFieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(fieldExpression); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync(fieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(fieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync(fieldExpression, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(fieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync( fieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(fieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync( fieldExpression, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(fieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync( fieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(fieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync( fieldExpression, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(fieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync( fieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(fieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync( fieldExpression, options, partitionKey, token)); } #region Keyed [Fact] public async Task Keyed_WithKeyedFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync, int>(keyedFieldExpression); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>(keyedFieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync, int>(keyedFieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>(keyedFieldExpression, null, null, token)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync, int>(keyedFieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync, int>(keyedFieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, options, null, token)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync, int>(keyedFieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync, int>(keyedFieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, null, partitionKey, token)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync, int>(keyedFieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync, int>(keyedFieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, options, partitionKey, token)); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/IndexTests/DropIndexAsyncTests.cs ================================================ using System; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests; public class DropIndexAsyncTests: BaseIndexTests { [Fact] public async Task WitIndexName_DropsIndex() { // Arrange var indexName = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync(indexName); // Assert IndexHandler.Verify( x => x.DropIndexAsync(indexName, null, CancellationToken.None)); } [Fact] public async Task WitIndexNameAndCancellationToken_DropsIndex() { // Arrange var indexName = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync(indexName, token); // Assert IndexHandler.Verify( x => x.DropIndexAsync(indexName, null, token)); } [Fact] public async Task WitIndexNameAndPartitionKey_DropsIndex() { // Arrange var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync(indexName, partitionKey); // Assert IndexHandler.Verify( x => x.DropIndexAsync(indexName, partitionKey, CancellationToken.None)); } [Fact] public async Task WitIndexNameAndPartitionKeyAndCancellationToken_DropsIndex() { // Arrange var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync(indexName, partitionKey, token); // Assert IndexHandler.Verify( x => x.DropIndexAsync(indexName, partitionKey, token)); } #region Keyed [Fact] public async Task Keyed_WithIndexName_DropsIndex() { // Arrange var indexName = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync, int>(indexName); // Assert IndexHandler.Verify( x => x.DropIndexAsync, int>(indexName, null, CancellationToken.None)); } [Fact] public async Task Keyed_WithIndexNameAndCancellationToken_DropsIndex() { // Arrange var indexName = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync, int>(indexName, token); // Assert IndexHandler.Verify( x => x.DropIndexAsync, int>(indexName, null, token)); } [Fact] public async Task Keyed_WithIndexNameAndPartitionKey_DropsIndex() { // Arrange var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync, int>(indexName, partitionKey); // Assert IndexHandler.Verify( x => x.DropIndexAsync, int>(indexName, partitionKey, CancellationToken.None)); } [Fact] public async Task Keyed_WithIndexNameAndPartitionKeyAndCancellationToken_DropsIndex() { // Arrange var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync, int>(indexName, partitionKey, token); // Assert IndexHandler.Verify( x => x.DropIndexAsync, int>(indexName, partitionKey, token)); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/IndexTests/GetIndexNamesAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests; public class GetIndexNamesAsyncTests : BaseIndexTests { [Fact] public async Task WithNoParameters_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); IndexHandler .Setup(x => x.GetIndexesNamesAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync(); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync(null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithCancellationToken_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); var token = new CancellationToken(true); IndexHandler .Setup(x => x.GetIndexesNamesAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync(token); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync(null, token), Times.Once()); } [Fact] public async Task WithPartitionKey_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); IndexHandler .Setup(x => x.GetIndexesNamesAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync(partitionKey); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync(partitionKey, CancellationToken.None), Times.Once()); } [Fact] public async Task WithPartitionKeyAndCancellationToken_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler .Setup(x => x.GetIndexesNamesAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync(partitionKey, token); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync(partitionKey, token), Times.Once()); } [Fact] public async Task Keyed_WithNoParameters_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); IndexHandler .Setup(x => x.GetIndexesNamesAsync, int>(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync, int>(); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync, int>(null, CancellationToken.None), Times.Once()); } [Fact] public async Task Keyed_WithCancellationToken_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); var token = new CancellationToken(true); IndexHandler .Setup(x => x.GetIndexesNamesAsync, int>(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync, int>(token); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync, int>(null, token), Times.Once()); } [Fact] public async Task Keyed_WithPartitionKey_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); IndexHandler .Setup(x => x.GetIndexesNamesAsync, int>(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync, int>(partitionKey); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync, int>(partitionKey, CancellationToken.None), Times.Once()); } [Fact] public async Task Keyed_WithPartitionKeyAndCancellationToken_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler .Setup(x => x.GetIndexesNamesAsync, int>(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync, int>(partitionKey, token); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync, int>(partitionKey, token), Times.Once()); } } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/UpdateTests/UpdateManyAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.UpdateTests; public class UpdateManyAsyncTests : TestMongoRepositoryContext { private readonly Expression> fieldExpression = x => x.SomeContent; private readonly FilterDefinition filterDefinition = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); private readonly Expression> filterExpression = x => x.SomeContent == "SomeContent"; private readonly UpdateDefinition updateDefinition = Builders.Update.Set(x => x.SomeContent, "Updated"); [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateManyAsync( filterDefinition, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateManyAsync( filterDefinition, fieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync( filterDefinition, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync( filterDefinition, fieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateManyAsync( filterExpression, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateManyAsync( filterExpression, fieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync( filterExpression, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync( filterExpression, fieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, updateDefinition); // Assert Updater.Verify( x => x.UpdateManyAsync( filterExpression, updateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateManyAsync( filterExpression, updateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, updateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync( filterExpression, updateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, updateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync( filterExpression, updateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, updateDefinition); // Assert Updater.Verify( x => x.UpdateManyAsync( filterDefinition, updateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndUpdateDefinitionCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateManyAsync( filterDefinition, updateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, updateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync( filterDefinition, updateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, updateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync( filterDefinition, updateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } #region Keyed private readonly UpdateDefinition> keyedUpdateDefinition = Builders>.Update.Set(x => x.SomeContent, "Updated"); private readonly Expression, string>> keyedFieldExpression = x => x.SomeContent; private readonly FilterDefinition> keyedFilterDefinition = Builders>.Filter.Eq(x => x.Id, 1); private readonly Expression, bool>> keyedFilterExpression = x => x.SomeContent == "SomeContent"; [Fact] public async Task Keyed_WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int, string>(keyedFilterDefinition, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( keyedFilterDefinition, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int, string>(keyedFilterDefinition, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( keyedFilterDefinition, keyedFieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int, string>(keyedFilterDefinition, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( keyedFilterDefinition, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int, string>(keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int, string>(keyedFilterExpression, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( keyedFilterExpression, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int, string>(keyedFilterExpression, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( keyedFilterExpression, keyedFieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int, string>(keyedFilterExpression, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( keyedFilterExpression, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int, string>(keyedFilterExpression, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( keyedFilterExpression, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterExpressionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int>(keyedFilterExpression, keyedUpdateDefinition); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( keyedFilterExpression, keyedUpdateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterExpressionAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int>(keyedFilterExpression, keyedUpdateDefinition, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( keyedFilterExpression, keyedUpdateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterExpressionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int>(keyedFilterExpression, keyedUpdateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( keyedFilterExpression, keyedUpdateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int>(keyedFilterExpression, keyedUpdateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( keyedFilterExpression, keyedUpdateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterDefinitionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int>(keyedFilterDefinition, keyedUpdateDefinition); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( keyedFilterDefinition, keyedUpdateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterDefinitionAndUpdateDefinitionCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int>(keyedFilterDefinition, keyedUpdateDefinition, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( keyedFilterDefinition, keyedUpdateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterDefinitionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int>(keyedFilterDefinition, keyedUpdateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( keyedFilterDefinition, keyedUpdateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task Keyed_WithFilterDefinitionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync, int>(keyedFilterDefinition, keyedUpdateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( keyedFilterDefinition, keyedUpdateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/UpdateTests/UpdateManyTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.UpdateTests; public class UpdateManyTests : TestMongoRepositoryContext { private readonly Expression> fieldExpression = x => x.SomeContent; private readonly FilterDefinition filterDefinition = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); private readonly Expression> filterExpression = x => x.SomeContent == "SomeContent"; private readonly UpdateDefinition updateDefinition = Builders.Update.Set(x => x.SomeContent, "Updated"); [Fact] public void WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateMany( filterDefinition, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateMany( filterDefinition, fieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateMany( filterDefinition, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany( filterDefinition, fieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateMany( filterExpression, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateMany( filterExpression, fieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateMany( filterExpression, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany( filterExpression, fieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, updateDefinition); // Assert Updater.Verify( x => x.UpdateMany( filterExpression, updateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateMany( filterExpression, updateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, updateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateMany( filterExpression, updateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, updateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany( filterExpression, updateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, updateDefinition); // Assert Updater.Verify( x => x.UpdateMany( filterDefinition, updateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndUpdateDefinitionCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateMany( filterDefinition, updateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, updateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateMany( filterDefinition, updateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, updateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany( filterDefinition, updateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } #region Keyed private readonly Expression, string>> keyedFieldExpression = x => x.SomeContent; private readonly FilterDefinition> keyedFilterDefinition = Builders>.Filter.Eq(x => x.Id, 1); private readonly Expression, bool>> keyedFilterExpression = x => x.SomeContent == "SomeContent"; private readonly UpdateDefinition> keyedUpdateDefinition = Builders>.Update.Set(x => x.SomeContent, "Updated"); [Fact] public void Keyed_WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int, string>(keyedFilterDefinition, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateMany, int, string>( keyedFilterDefinition, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int, string>(keyedFilterDefinition, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateMany, int, string>( keyedFilterDefinition, keyedFieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int, string>(keyedFilterDefinition, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateMany, int, string>( keyedFilterDefinition, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int, string>(keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany, int, string>( keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int, string>(keyedFilterExpression, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateMany, int, string>( keyedFilterExpression, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int, string>(keyedFilterExpression, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateMany, int, string>( keyedFilterExpression, keyedFieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int, string>(keyedFilterExpression, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateMany, int, string>( keyedFilterExpression, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int, string>(keyedFilterExpression, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany, int, string>( keyedFilterExpression, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterExpressionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int>(keyedFilterExpression, keyedUpdateDefinition); // Assert Updater.Verify( x => x.UpdateMany, int>( keyedFilterExpression, keyedUpdateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterExpressionAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int>(keyedFilterExpression, keyedUpdateDefinition, token); // Assert Updater.Verify( x => x.UpdateMany, int>( keyedFilterExpression, keyedUpdateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterExpressionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int>(keyedFilterExpression, keyedUpdateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateMany, int>( keyedFilterExpression, keyedUpdateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int>(keyedFilterExpression, keyedUpdateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany, int>( keyedFilterExpression, keyedUpdateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterDefinitionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int>(keyedFilterDefinition, keyedUpdateDefinition); // Assert Updater.Verify( x => x.UpdateMany, int>( keyedFilterDefinition, keyedUpdateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterDefinitionAndUpdateDefinitionCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int>(keyedFilterDefinition, keyedUpdateDefinition, token); // Assert Updater.Verify( x => x.UpdateMany, int>( keyedFilterDefinition, keyedUpdateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterDefinitionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int>(keyedFilterDefinition, keyedUpdateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateMany, int>( keyedFilterDefinition, keyedUpdateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterDefinitionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany, int>(keyedFilterDefinition, keyedUpdateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany, int>( keyedFilterDefinition, keyedUpdateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/UpdateTests/UpdateOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.UpdateTests; public class UpdateOneAsyncTests : TestMongoRepositoryContext { private readonly UpdateDefinition updateDefinition = Builders.Update.Set(x => x.SomeContent, "Updated"); private readonly Expression> fieldExpression = x => x.SomeContent; private readonly FilterDefinition filterDefinition = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); private readonly Expression> filterExpression = x => x.SomeContent == "SomeContent"; [Fact] public async Task WithDocument_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); Updater = new Mock(); Updater .Setup(x => x.UpdateOneAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document); // Assert Updater.Verify(x => x.UpdateOneAsync(document, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup(x => x.UpdateOneAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, token); // Assert Updater.Verify(x => x.UpdateOneAsync(document, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndUpdateDefinition_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny(), It.IsAny>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, updateDefinition); // Assert Updater.Verify( x => x.UpdateOneAsync( document, updateDefinition, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny(), It.IsAny>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateOneAsync( document, updateDefinition, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync( document, fieldExpression, value, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync( document, fieldExpression, value, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterDefinition, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync( filterDefinition, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterDefinition, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync( filterDefinition, fieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterDefinition, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOneAsync( filterDefinition, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterDefinition, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOneAsync( filterDefinition, fieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterExpression, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync( filterExpression, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterExpression, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync( filterExpression, fieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterExpression, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOneAsync( filterExpression, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterExpression, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOneAsync( filterExpression, fieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } #region Keyed private readonly UpdateDefinition> keyedUpdateDefinition = Builders>.Update.Set(x => x.SomeContent, "Updated"); private readonly Expression, string>> keyedFieldExpression = x => x.SomeContent; private readonly FilterDefinition> keyedFilterDefinition = Builders>.Filter.Eq(x => x.Id, 1); private readonly Expression, bool>> keyedFilterExpression = x => x.SomeContent == "SomeContent"; [Fact] public async Task Keyed_WithDocument_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup(x => x.UpdateOneAsync, int>(It.IsAny>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int>(document); // Assert Updater.Verify(x => x.UpdateOneAsync, int>(document, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithDocumentAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup(x => x.UpdateOneAsync, int>(It.IsAny>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int>(document, token); // Assert Updater.Verify(x => x.UpdateOneAsync, int>(document, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithDocumentAndUpdateDefinition_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int>( It.IsAny>(), It.IsAny>>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int>(document, keyedUpdateDefinition); // Assert Updater.Verify( x => x.UpdateOneAsync, int>( document, keyedUpdateDefinition, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithDocumentAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int>( It.IsAny>(), It.IsAny>>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int>(document, keyedUpdateDefinition, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int>( document, keyedUpdateDefinition, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithDocumentAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(document, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( document, keyedFieldExpression, value, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithDocumentAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(document, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( document, keyedFieldExpression, value, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(keyedFilterDefinition, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( keyedFilterDefinition, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(keyedFilterDefinition, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( keyedFilterDefinition, keyedFieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(keyedFilterDefinition, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( keyedFilterDefinition, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(keyedFilterExpression, keyedFieldExpression, value); // Assert var expectedFilter = Builders>.Filter.Where(keyedFilterExpression); Updater.Verify( x => x.UpdateOneAsync, int, string>( It.Is>>(y => y.EquivalentTo(expectedFilter)), keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(keyedFilterExpression, keyedFieldExpression, value, token); // Assert var expectedFilter = Builders>.Filter.Where(keyedFilterExpression); Updater.Verify( x => x.UpdateOneAsync, int, string>( It.Is>>(y => y.EquivalentTo(expectedFilter)), keyedFieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(keyedFilterExpression, keyedFieldExpression, value, partitionKey); // Assert var expectedFilter = Builders>.Filter.Where(keyedFilterExpression); Updater.Verify( x => x.UpdateOneAsync, int, string>( It.Is>>(y => y.EquivalentTo(expectedFilter)), keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(keyedFilterExpression, keyedFieldExpression, value, partitionKey, token); // Assert var expectedFilter = Builders>.Filter.Where(keyedFilterExpression); Updater.Verify( x => x.UpdateOneAsync, int, string>( It.Is>>(y => y.EquivalentTo(expectedFilter)), keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } #endregion #region ClientSession [Fact] public async Task Keyed_WithClientSessionHandlerAndDocument_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup(x => x.UpdateOneAsync, int>( It.IsAny(), It.IsAny>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int>(session, document); // Assert Updater.Verify( x => x.UpdateOneAsync, int>( session, document, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndDocumentAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup(x => x.UpdateOneAsync, int>( It.IsAny(), It.IsAny>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int>(session, document, token); // Assert Updater.Verify(x => x.UpdateOneAsync, int>(session, document, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndDocumentAndUpdateDefinition_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int>( It.IsAny(), It.IsAny>(), It.IsAny>>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int>(session, document, keyedUpdateDefinition); // Assert Updater.Verify( x => x.UpdateOneAsync, int>( session, document, keyedUpdateDefinition, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndDocumentAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int>( It.IsAny(), It.IsAny>(), It.IsAny>>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int>(session, document, keyedUpdateDefinition, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int>( session, document, keyedUpdateDefinition, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndDocumentAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, document, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, document, keyedFieldExpression, value, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndDocumentAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, document, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, document, keyedFieldExpression, value, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, keyedFilterDefinition, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, keyedFilterDefinition, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, keyedFilterDefinition, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, keyedFilterDefinition, keyedFieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, keyedFilterDefinition, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, keyedFilterDefinition, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, keyedFilterExpression, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, keyedFilterExpression, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, keyedFilterExpression, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, keyedFilterExpression, keyedFieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, keyedFilterExpression, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, keyedFilterExpression, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task Keyed_WithClientSessionHandlerAndFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny(), It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync, int, string>(session, keyedFilterExpression, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( session, keyedFilterExpression, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } #endregion } ================================================ FILE: CoreUnitTests/BaseMongoRepositoryTests/UpdateTests/UpdateOneTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.BaseMongoRepositoryTests.UpdateTests; public class UpdateOneTests : TestMongoRepositoryContext { private readonly UpdateDefinition updateDefinition = Builders.Update.Set(x => x.SomeContent, "Updated"); private readonly Expression> fieldExpression = x => x.SomeContent; private readonly FilterDefinition filterDefinition = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); private readonly Expression> filterExpression = x => x.SomeContent == "SomeContent"; [Fact] public void WithDocument_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); Updater = new Mock(); Updater .Setup(x => x.UpdateOne(It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document); // Assert Updater.Verify(x => x.UpdateOne(document, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup(x => x.UpdateOne(It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, token); // Assert Updater.Verify(x => x.UpdateOne(document, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndUpdateDefinition_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny(), It.IsAny>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, updateDefinition); // Assert Updater.Verify( x => x.UpdateOne( document, updateDefinition, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny(), It.IsAny>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateOne( document, updateDefinition, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne( document, fieldExpression, value, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne( document, fieldExpression, value, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterDefinition, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne( filterDefinition, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterDefinition, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne( filterDefinition, fieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterDefinition, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOne( filterDefinition, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterDefinition, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOne( filterDefinition, fieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterExpression, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne( filterExpression, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterExpression, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne( filterExpression, fieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterExpression, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOne( filterExpression, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterExpression, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOne( filterExpression, fieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } #region Keyed private readonly UpdateDefinition> keyedUpdateDefinition = Builders>.Update.Set(x => x.SomeContent, "Updated"); private readonly Expression, string>> keyedFieldExpression = x => x.SomeContent; private readonly FilterDefinition> keyedFilterDefinition = Builders>.Filter.Eq(x => x.Id, 1); private readonly Expression, bool>> keyedFilterExpression = x => x.SomeContent == "SomeContent"; [Fact] public void Keyed_WithDocument_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup(x => x.UpdateOne, int>(It.IsAny>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int>(document); // Assert Updater.Verify(x => x.UpdateOne, int>(document, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithDocumentAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup(x => x.UpdateOne, int>(It.IsAny>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int>(document, token); // Assert Updater.Verify(x => x.UpdateOne, int>(document, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithDocumentAndUpdateDefinition_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int>( It.IsAny>(), It.IsAny>>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int>(document, keyedUpdateDefinition); // Assert Updater.Verify( x => x.UpdateOne, int>( document, keyedUpdateDefinition, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithDocumentAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int>( It.IsAny>(), It.IsAny>>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int>(document, keyedUpdateDefinition, token); // Assert Updater.Verify( x => x.UpdateOne, int>( document, keyedUpdateDefinition, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithDocumentAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(document, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne, int, string>( document, keyedFieldExpression, value, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithDocumentAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(document, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( document, keyedFieldExpression, value, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(keyedFilterDefinition, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne, int, string>( keyedFilterDefinition, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(keyedFilterDefinition, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( keyedFilterDefinition, keyedFieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(keyedFilterDefinition, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOne, int, string>( keyedFilterDefinition, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(keyedFilterExpression, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne, int, string>( keyedFilterExpression, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(keyedFilterExpression, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( keyedFilterExpression, keyedFieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(keyedFilterExpression, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOne, int, string>( keyedFilterExpression, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(keyedFilterExpression, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( keyedFilterExpression, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } #endregion #region client session [Fact] public void Keyed_WithClientSessionHandlerAndDocument_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var session = new Mock().Object; Updater = new Mock(); Updater .Setup(x => x.UpdateOne, int>( It.IsAny(), It.IsAny>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int>(session, document); // Assert Updater.Verify(x => x.UpdateOne, int>( session, document, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerAndDocumentAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); var session = new Mock().Object; Updater = new Mock(); Updater .Setup(x => x.UpdateOne, int>( It.IsAny(), It.IsAny>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int>(session, document, token); // Assert Updater.Verify(x => x.UpdateOne, int>(session, document, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerAndDocumentAndUpdateDefinition_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int>( It.IsAny(), It.IsAny>(), It.IsAny>>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int>(session, document, keyedUpdateDefinition); // Assert Updater.Verify( x => x.UpdateOne, int>( session, document, keyedUpdateDefinition, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerAndDocumentAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int>( It.IsAny(), It.IsAny>(), It.IsAny>>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int>(session, document, keyedUpdateDefinition, token); // Assert Updater.Verify( x => x.UpdateOne, int>( session, document, keyedUpdateDefinition, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerAndDocumentAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, document, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne, int, string>( session, document, keyedFieldExpression, value, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerAndDocumentAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var document = Fixture.Create>(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, document, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( session, document, keyedFieldExpression, value, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, keyedFilterDefinition, keyedFieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne, int, string>( session, keyedFilterDefinition, keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, keyedFilterDefinition, keyedFieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( session, keyedFilterDefinition, keyedFieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, keyedFilterDefinition, keyedFieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOne, int, string>( session, keyedFilterDefinition, keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( session, keyedFilterDefinition, keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, keyedFilterExpression, keyedFieldExpression, value); // Assert var expectedFilterDefinition = new ExpressionFilterDefinition>(keyedFilterExpression); Updater.Verify( x => x.UpdateOne, int, string>( session, It.Is>>(y => y.EquivalentTo(expectedFilterDefinition)), keyedFieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, keyedFilterExpression, keyedFieldExpression, value, token); // Assert var expectedFilterDefinition = new ExpressionFilterDefinition>(keyedFilterExpression); Updater.Verify( x => x.UpdateOne, int, string>( session, It.Is>>(y => y.EquivalentTo(expectedFilterDefinition)), keyedFieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, keyedFilterExpression, keyedFieldExpression, value, partitionKey); // Assert var expectedFilterDefinition = new ExpressionFilterDefinition>(keyedFilterExpression); Updater.Verify( x => x.UpdateOne, int, string>( session, It.Is>>(y => y.EquivalentTo(expectedFilterDefinition)), keyedFieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void Keyed_WithClientSessionHandlerFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var session = new Mock().Object; var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny(), It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne, int, string>(session, keyedFilterExpression, keyedFieldExpression, value, partitionKey, token); // Assert var expectedFilterDefinition = new ExpressionFilterDefinition>(keyedFilterExpression); Updater.Verify( x => x.UpdateOne, int, string>( session, It.Is>>(y => y.EquivalentTo(expectedFilterDefinition)), keyedFieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } #endregion } ================================================ FILE: CoreUnitTests/CoreUnitTests.csproj ================================================ net8.0 warnings enable false true latest all runtime; build; native; contentfiles; analyzers all runtime; build; native; contentfiles; analyzers; buildtransitive runtime; build; native; contentfiles; analyzers; buildtransitive all ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbCreatorTests/AddManyAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbCreatorTests; public class AddManyAsyncTests : GenericTestContext { [Fact] public async Task WithDocuments_AddsMany() { // Arrange var documents = Fixture.CreateMany().ToList(); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddManyAsync(documents); // Assert collection.Verify( x => x.InsertManyAsync( It.Is>(l => l.All(d => documents.Contains(d))), null, default), Times.Once()); } [Fact] public async Task WithDocumentsHavingNoId_SetsId() { // Arrange var documents = Fixture .Build>() .Without(x => x.Id) .CreateMany() .ToList(); var context = MockOf(); var collection = MockOf>>(); context .Setup(x => x.GetCollection>(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddManyAsync, string>(documents); // Assert collection.Verify( x => x.InsertManyAsync( It.Is>>(l => l.All(d => documents.Contains(d))), null, default), Times.Once()); documents.Should().AllSatisfy(d => d.Id.Should().NotBeNull()); } [Fact] public async Task WithPartitionedDocument_AddsMany() { // Arrange var partitionKey = Fixture.Create(); var documents = Fixture.Build() .With(x => x.PartitionKey, partitionKey) .CreateMany() .ToList(); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddManyAsync(documents); // Assert collection.Verify( x => x.InsertManyAsync( It.Is>(l => l.All(d => documents.Contains(d))), null, default), Times.Once()); context.Verify(x => x.GetCollection(partitionKey), Times.Once()); } [Fact] public async Task WithDocumentsAndCancellationToken_AddsMany() { // Arrange var documents = Fixture.CreateMany().ToList(); var context = MockOf(); var collection = MockOf>(); var token = new CancellationToken(true); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddManyAsync(documents, token); // Assert collection.Verify( x => x.InsertManyAsync( It.Is>(l => l.All(d => documents.Contains(d))), null, token), Times.Once()); } [Fact] public async Task WithPartitionedDocumentAndCancellationToken_AddsOne() { // Arrange var partitionKey = Fixture.Create(); var documents = Fixture.Build() .With(x => x.PartitionKey, partitionKey) .CreateMany() .ToList(); var token = new CancellationToken(true); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddManyAsync(documents, token); // Assert collection.Verify( x => x.InsertManyAsync( It.Is>(l => l.All(d => documents.Contains(d))), null, token), Times.Once()); context.Verify(x => x.GetCollection(partitionKey), Times.Once()); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbCreatorTests/AddManyTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbCreatorTests; public class AddManyTests : GenericTestContext { [Fact] public void WithDocuments_AddsMany() { // Arrange var documents = Fixture.CreateMany().ToList(); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act Sut.AddMany(documents); // Assert collection.Verify( x => x.InsertMany( It.Is>(l => l.All(d => documents.Contains(d))), null, default), Times.Once()); } [Fact] public void WithDocumentsHavingNoId_SetsId() { // Arrange var documents = Fixture .Build>() .Without(x => x.Id) .CreateMany() .ToList(); var context = MockOf(); var collection = MockOf>>(); context .Setup(x => x.GetCollection>(It.IsAny())) .Returns(collection.Object); // Act Sut.AddMany, string>(documents); // Assert collection.Verify( x => x.InsertMany( It.Is>>(l => l.All(d => documents.Contains(d))), null, default), Times.Once()); documents.Should().AllSatisfy(d => d.Id.Should().NotBeNull()); } [Fact] public void WithPartitionedDocument_AddsMany() { // Arrange var partitionKey = Fixture.Create(); var documents = Fixture.Build() .With(x => x.PartitionKey, partitionKey) .CreateMany() .ToList(); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act Sut.AddMany(documents); // Assert collection.Verify( x => x.InsertMany( It.Is>(l => l.All(d => documents.Contains(d))), null, default), Times.Once()); context.Verify(x => x.GetCollection(partitionKey), Times.Once()); } [Fact] public void WithDocumentsAndCancellationToken_AddsMany() { // Arrange var documents = Fixture.CreateMany().ToList(); var context = MockOf(); var collection = MockOf>(); var token = new CancellationToken(true); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act Sut.AddMany(documents, token); // Assert collection.Verify( x => x.InsertMany( It.Is>(l => l.All(d => documents.Contains(d))), null, token), Times.Once()); } [Fact] public void WithPartitionedDocumentAndCancellationToken_AddsOne() { // Arrange var partitionKey = Fixture.Create(); var documents = Fixture.Build() .With(x => x.PartitionKey, partitionKey) .CreateMany() .ToList(); var token = new CancellationToken(true); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act Sut.AddMany(documents, token); // Assert collection.Verify( x => x.InsertMany( It.Is>(l => l.All(d => documents.Contains(d))), null, token), Times.Once()); context.Verify(x => x.GetCollection(partitionKey), Times.Once()); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbCreatorTests/AddOneAsyncTests.cs ================================================ using System; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbCreatorTests; public class AddOneAsyncTests : GenericTestContext { [Fact] public async Task WithDocument_AddsOne() { // Arrange var document = new TestDocument(); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddOneAsync(document); // Assert collection.Verify( x => x.InsertOneAsync( It.Is(d => d == document), null, default), Times.Once()); } [Fact] public async Task WithDocumentHavingNoId_SetsId() { // Arrange var document = new TestDocumentWithKey(); var context = MockOf(); var collection = MockOf>>(); context .Setup(x => x.GetCollection>(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddOneAsync, string>(document); // Assert collection.Verify( x => x.InsertOneAsync( It.Is>(d => d == document), null, default), Times.Once()); document.Id.Should().NotBeNull(); } [Fact] public async Task WithPartitionedDocument_AddsOne() { // Arrange var partitionKey = Fixture.Create(); var document = Fixture.Build() .With(x => x.PartitionKey, partitionKey) .Create(); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddOneAsync(document); // Assert collection.Verify( x => x.InsertOneAsync( It.Is(d => d == document), null, default), Times.Once()); context.Verify(x => x.GetCollection(partitionKey), Times.Once()); } [Fact] public async Task WithDocumentAndCancellationToken_AddsOne() { // Arrange var document = new TestDocument(); var context = MockOf(); var collection = MockOf>(); var token = new CancellationToken(true); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddOneAsync(document, token); // Assert collection.Verify( x => x.InsertOneAsync( It.Is(d => d == document), null, token), Times.Once()); } [Fact] public async Task WithPartitionedDocumentAndCancellationToken_AddsOne() { // Arrange var partitionKey = Fixture.Create(); var document = Fixture.Build() .With(x => x.PartitionKey, partitionKey) .Create(); var token = new CancellationToken(true); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act await Sut.AddOneAsync(document, token); // Assert collection.Verify( x => x.InsertOneAsync( It.Is(d => d == document), null, token), Times.Once()); context.Verify(x => x.GetCollection(partitionKey), Times.Once()); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbCreatorTests/AddOneTests.cs ================================================ using System; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbCreatorTests; public class AddOneTests : GenericTestContext { [Fact] public void WithDocument_AddsOne() { // Arrange var document = new TestDocument(); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act Sut.AddOne(document); // Assert collection.Verify( x => x.InsertOne( It.Is(d => d == document), null, default), Times.Once()); } [Fact] public void WithDocumentHavingNoId_SetsId() { // Arrange var document = new TestDocumentWithKey(); var context = MockOf(); var collection = MockOf>>(); context .Setup(x => x.GetCollection>(It.IsAny())) .Returns(collection.Object); // Act Sut.AddOne, string>(document); // Assert collection.Verify( x => x.InsertOne( It.Is>(d => d == document), null, default), Times.Once()); document.Id.Should().NotBeNull(); } [Fact] public void WithPartitionedDocument_AddsOne() { // Arrange var partitionKey = Fixture.Create(); var document = Fixture.Build() .With(x => x.PartitionKey, partitionKey) .Create(); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act Sut.AddOne(document); // Assert collection.Verify( x => x.InsertOne( It.Is(d => d == document), null, default), Times.Once()); context.Verify(x => x.GetCollection(partitionKey), Times.Once()); } [Fact] public void WithDocumentAndCancellationToken_AddsOne() { // Arrange var document = new TestDocument(); var context = MockOf(); var collection = MockOf>(); var token = new CancellationToken(true); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act Sut.AddOne(document, token); // Assert collection.Verify( x => x.InsertOne( It.Is(d => d == document), null, token), Times.Once()); } [Fact] public void WithPartitionedDocumentAndCancellationToken_AddsOne() { // Arrange var partitionKey = Fixture.Create(); var document = Fixture.Build() .With(x => x.PartitionKey, partitionKey) .Create(); var token = new CancellationToken(true); var context = MockOf(); var collection = MockOf>(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act Sut.AddOne(document, token); // Assert collection.Verify( x => x.InsertOne( It.Is(d => d == document), null, token), Times.Once()); context.Verify(x => x.GetCollection(partitionKey), Times.Once()); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbEraserTests/DeleteManyAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbEraserTests; public class DeleteManyAsyncTests : GenericTestContext { [Fact] public async Task WithEmptyDocuments_DeletesNothing() { // Arrange var documents = new List(0); var token = new CancellationToken(true); var collection = MockOf>(); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(null)) .Returns(collection.Object); // Act var result = await Sut.DeleteManyAsync(documents, token); // Assert result.Should().Be(0); var idsToDelete = documents.Select(e => e.Id).ToArray(); Expression> expectedFilter = x => idsToDelete.Contains(x.Id); collection.Verify( x => x.DeleteManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), token), Times.Never); } [Fact] public async Task WithDocumentsAndCancellationToken_DeletesMany() { // Arrange var count = Fixture.Create(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteManyAsync(It.IsAny>(), It.IsAny())) .ReturnsAsync(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(null)) .Returns(collection.Object); // Act var result = await Sut.DeleteManyAsync(documents, token); // Assert result.Should().Be(count); var idsToDelete = documents.Select(e => e.Id).ToArray(); Expression> expectedFilter = x => idsToDelete.Contains(x.Id); collection.Verify( x => x.DeleteManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), token), Times.Once); } [Fact] public async Task WithPartitionDocumentsAndCancellationToken_DeletesMany() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var documents = Fixture .Build() .With(x => x.PartitionKey, partitionKey) .CreateMany() .ToList(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteManyAsync(It.IsAny>(), It.IsAny())) .ReturnsAsync(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act var result = await Sut.DeleteManyAsync(documents, token); // Assert result.Should().Be(count); var idsToDelete = documents.Select(e => e.Id).ToArray(); Expression> expectedFilter = x => idsToDelete.Contains(x.Id); collection.Verify( x => x.DeleteManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), token), Times.Once); dbContext.Verify(x => x.GetCollection(partitionKey), Times.Once); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_DeletesOne() { // Arrange var count = Fixture.Create(); var id = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteManyAsync(It.IsAny>(), It.IsAny())) .ReturnsAsync(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); Expression> filter = d => d.Id == id; // Act var result = await Sut.DeleteManyAsync(filter, partitionKey, token); // Assert result.Should().Be(count); collection.Verify( x => x.DeleteManyAsync( It.Is>(f => f.EquivalentTo(filter)), token), Times.Once); dbContext.Verify(x => x.GetCollection(partitionKey), Times.Once); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbEraserTests/DeleteManyTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbEraserTests; public class DeleteManyTests : GenericTestContext { [Fact] public void WithEmptyDocuments_DeletesNothing() { // Arrange var documents = new List(0); var token = new CancellationToken(true); var collection = MockOf>(); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(null)) .Returns(collection.Object); // Act var result = Sut.DeleteMany(documents, token); // Assert result.Should().Be(0); var idsToDelete = documents.Select(e => e.Id).ToArray(); Expression> expectedFilter = x => idsToDelete.Contains(x.Id); collection.Verify( x => x.DeleteMany( It.Is>(f => f.EquivalentTo(expectedFilter)), token), Times.Never); } [Fact] public void WithDocumentsAndCancellationToken_DeletesMany() { // Arrange var count = Fixture.Create(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteMany(It.IsAny>(), It.IsAny())) .Returns(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(null)) .Returns(collection.Object); // Act var result = Sut.DeleteMany(documents, token); // Assert result.Should().Be(count); var idsToDelete = documents.Select(e => e.Id).ToArray(); Expression> expectedFilter = x => idsToDelete.Contains(x.Id); collection.Verify( x => x.DeleteMany( It.Is>(f => f.EquivalentTo(expectedFilter)), token), Times.Once); } [Fact] public void WithPartitionDocumentsAndCancellationToken_DeletesMany() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var documents = Fixture .Build() .With(x => x.PartitionKey, partitionKey) .CreateMany() .ToList(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteMany(It.IsAny>(), It.IsAny())) .Returns(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); // Act var result = Sut.DeleteMany(documents, token); // Assert result.Should().Be(count); var idsToDelete = documents.Select(e => e.Id).ToArray(); Expression> expectedFilter = x => idsToDelete.Contains(x.Id); collection.Verify( x => x.DeleteMany( It.Is>(f => f.EquivalentTo(expectedFilter)), token), Times.Once); dbContext.Verify(x => x.GetCollection(partitionKey), Times.Once); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_DeletesOne() { // Arrange var count = Fixture.Create(); var id = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteMany(It.IsAny>(), It.IsAny())) .Returns(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); Expression> filter = d => d.Id == id; // Act var result = Sut.DeleteMany(filter, partitionKey, token); // Assert result.Should().Be(count); collection.Verify( x => x.DeleteMany( It.Is>(f => f.EquivalentTo(filter)), token), Times.Once); dbContext.Verify(x => x.GetCollection(partitionKey), Times.Once); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbEraserTests/DeleteOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbEraserTests; public class DeleteOneAsyncTests : GenericTestContext { [Fact] public async Task WithDocumentAndCancellationToken_DeletesOne() { // Arrange var count = Fixture.Create(); var document = Fixture.Create(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteOneAsync(It.IsAny>(), It.IsAny())) .ReturnsAsync(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(null)) .Returns(collection.Object); // Act var result = await Sut.DeleteOneAsync(document, token); // Assert result.Should().Be(count); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection.Verify( x => x.DeleteOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), token), Times.Once()); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_DeletesOne() { // Arrange var count = Fixture.Create(); var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteOneAsync(It.IsAny>(), It.IsAny())) .ReturnsAsync(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); Expression> filter = d => d.Id == document.Id; // Act var result = await Sut.DeleteOneAsync(filter, partitionKey, token); // Assert result.Should().Be(count); collection.Verify( x => x.DeleteOneAsync( It.Is>(f => f.EquivalentTo(filter)), token), Times.Once()); dbContext.Verify(x => x.GetCollection(partitionKey)); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbEraserTests/DeleteOneTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbEraserTests; public class DeleteOneTests : GenericTestContext { [Fact] public void WithDocumentAndCancellationToken_DeletesOne() { // Arrange var count = Fixture.Create(); var document = Fixture.Create(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteOne(It.IsAny>(), It.IsAny())) .Returns(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(null)) .Returns(collection.Object); // Act var result = Sut.DeleteOne(document, token); // Assert result.Should().Be(count); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection.Verify( x => x.DeleteOne( It.Is>(f => f.EquivalentTo(expectedFilter)), token), Times.Once()); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_DeletesOne() { // Arrange var count = Fixture.Create(); var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var collection = MockOf>(); collection .Setup(x => x.DeleteOne(It.IsAny>(), It.IsAny())) .Returns(new DeleteResult.Acknowledged(count)); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); Expression> filter = d => d.Id == document.Id; // Act var result = Sut.DeleteOne(filter, partitionKey, token); // Assert result.Should().Be(count); collection.Verify( x => x.DeleteOne( It.Is>(f => f.EquivalentTo(filter)), token), Times.Once()); dbContext.Verify(x => x.GetCollection(partitionKey)); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbIndexHandlerTests/BaseIndexTests.cs ================================================ using System.Collections.Generic; using System.Threading; using CoreUnitTests.Infrastructure; using MongoDB.Bson; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Index; using Moq; namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests; public class BaseIndexTests : GenericTestContext { protected (Mock>, Mock>) SetupIndexes( List indexes, Mock> collection) { var asyncCursor = MockOf>(); var moveNextSequence = asyncCursor .SetupSequence(x => x.MoveNextAsync(It.IsAny())); var currentSequence = asyncCursor .SetupSequence(x => x.Current); foreach (var bsonDocument in indexes) { moveNextSequence.ReturnsAsync(true); currentSequence.Returns(new[] {bsonDocument}); } moveNextSequence.ReturnsAsync(false); var indexManager = MockOf>(); indexManager .Setup(x => x.ListAsync(It.IsAny())) .ReturnsAsync(asyncCursor.Object); collection .SetupGet(x => x.Indexes) .Returns(indexManager.Object); return (asyncCursor, indexManager); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbIndexHandlerTests/CreateAscendingIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests; public class CreateAscendingIndexAsyncTests : BaseIndexTests { private readonly Expression> fieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateAscendingIndexAsync(fieldExpression); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>(t => t.Keys.EqualToJson("{\"SomeContent2\":1}")), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var options = Fixture.Create(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateAscendingIndexAsync(fieldExpression, options); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":1}") && t.Options.EqualTo(options)), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateAscendingIndexAsync(fieldExpression, partitionKey: partitionKey); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":1}") ), null, CancellationToken.None), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateAscendingIndexAsync(fieldExpression, cancellationToken: token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":1}") ), null, token), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var partitionKey = Fixture.Create(); var options = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateAscendingIndexAsync(fieldExpression, options, partitionKey, token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":1}") && t.Options.EqualTo(options)), null, token), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } private Mock SetupContext(Mock> collection) { var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); return context; } private Mock> SetupIndexManager(Mock> collection, string indexName) { var indexManager = MockOf>(); indexManager .Setup( x => x.CreateOneAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(indexName); collection .SetupGet(x => x.Indexes) .Returns(indexManager.Object); return indexManager; } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbIndexHandlerTests/CreateCombinedTextIndexAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.Models; using Moq; using Xunit; using Xunit.Abstractions; namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests; public class CreateCombinedTextIndexAsyncTests : BaseIndexTests { private readonly ITestOutputHelper testOutputHelper; private readonly List>> fieldExpressions = new() { t => t.SomeContent2, t => t.GroupingKey }; public CreateCombinedTextIndexAsyncTests(ITestOutputHelper testOutputHelper) => this.testOutputHelper = testOutputHelper; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateCombinedTextIndexAsync(fieldExpressions); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>(t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}", testOutputHelper)), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var options = Fixture.Create(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}") && t.Options.EqualTo(options)), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateCombinedTextIndexAsync(fieldExpressions, partitionKey: partitionKey); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}") ), null, CancellationToken.None), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateCombinedTextIndexAsync(fieldExpressions, cancellationToken: token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}") ), null, token), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var partitionKey = Fixture.Create(); var options = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options, partitionKey, token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}") && t.Options.EqualTo(options)), null, token), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } private Mock SetupContext(Mock> collection) { var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); return context; } private Mock> SetupIndexManager(Mock> collection, string indexName) { var indexManager = MockOf>(); indexManager .Setup( x => x.CreateOneAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(indexName); collection .SetupGet(x => x.Indexes) .Returns(indexManager.Object); return indexManager; } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbIndexHandlerTests/CreateDescendingIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests; public class CreateDescendingIndexAsyncTests : BaseIndexTests { private readonly Expression> fieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateDescendingIndexAsync(fieldExpression); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>(t => t.Keys.EqualToJson("{\"SomeContent2\":-1}")), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var options = Fixture.Create(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateDescendingIndexAsync(fieldExpression, options); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":-1}") && t.Options.EqualTo(options)), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateDescendingIndexAsync(fieldExpression, partitionKey: partitionKey); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":-1}") ), null, CancellationToken.None), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateDescendingIndexAsync(fieldExpression, cancellationToken: token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":-1}") ), null, token), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var partitionKey = Fixture.Create(); var options = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateDescendingIndexAsync(fieldExpression, options, partitionKey, token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":-1}") && t.Options.EqualTo(options)), null, token), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } private Mock SetupContext(Mock> collection) { var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); return context; } private Mock> SetupIndexManager(Mock> collection, string indexName) { var indexManager = MockOf>(); indexManager .Setup( x => x.CreateOneAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(indexName); collection .SetupGet(x => x.Indexes) .Returns(indexManager.Object); return indexManager; } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbIndexHandlerTests/CreateHashedIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.Models; using Moq; using Xunit; using Xunit.Abstractions; namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests; public class CreateHashedIndexAsyncTests : BaseIndexTests { private readonly ITestOutputHelper testOutputHelper; private readonly Expression> fieldExpression = t => t.SomeContent2; public CreateHashedIndexAsyncTests(ITestOutputHelper testOutputHelper) => this.testOutputHelper = testOutputHelper; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateHashedIndexAsync(fieldExpression); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>(t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}", testOutputHelper)), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var options = Fixture.Create(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateHashedIndexAsync(fieldExpression, options); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}") && t.Options.EqualTo(options)), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateHashedIndexAsync(fieldExpression, partitionKey: partitionKey); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}") ), null, CancellationToken.None), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateHashedIndexAsync(fieldExpression, cancellationToken: token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}") ), null, token), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var partitionKey = Fixture.Create(); var options = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateHashedIndexAsync(fieldExpression, options, partitionKey, token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}") && t.Options.EqualTo(options)), null, token), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } private Mock SetupContext(Mock> collection) { var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); return context; } private Mock> SetupIndexManager(Mock> collection, string indexName) { var indexManager = MockOf>(); indexManager .Setup( x => x.CreateOneAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(indexName); collection .SetupGet(x => x.Indexes) .Returns(indexManager.Object); return indexManager; } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbIndexHandlerTests/CreateTextIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests; public class CreateTextIndexAsyncTests : BaseIndexTests { private readonly Expression> fieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateTextIndexAsync(fieldExpression); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>(t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}")), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var options = Fixture.Create(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateTextIndexAsync(fieldExpression, options); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}") && t.Options.EqualTo(options)), null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateTextIndexAsync(fieldExpression, partitionKey: partitionKey); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}") ), null, CancellationToken.None), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateTextIndexAsync(fieldExpression, cancellationToken: token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}") ), null, token), Times.Once); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var partitionKey = Fixture.Create(); var options = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act var result = await Sut.CreateTextIndexAsync(fieldExpression, options, partitionKey, token); // Assert result.Should().Be(expectedIndexName); indexManger.Verify( x => x.CreateOneAsync( It.Is>( t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}") && t.Options.EqualTo(options)), null, token), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } private Mock SetupContext(Mock> collection) { var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); return context; } private Mock> SetupIndexManager(Mock> collection, string indexName) { var indexManager = MockOf>(); indexManager .Setup( x => x.CreateOneAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(indexName); collection .SetupGet(x => x.Indexes) .Returns(indexManager.Object); return indexManager; } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbIndexHandlerTests/DropIndexAsyncTests.cs ================================================ using System; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests; public class DropIndexAsyncTests : BaseIndexTests { [Fact] public async Task WithIndexName_DropsIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act await Sut.DropIndexAsync(expectedIndexName); // Assert indexManger.Verify(x => x.DropOneAsync(expectedIndexName, CancellationToken.None), Times.Once); } [Fact] public async Task WithIndexNameAndPartitionKey_DropsIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act await Sut.DropIndexAsync(expectedIndexName, partitionKey); // Assert indexManger.Verify(x => x.DropOneAsync(expectedIndexName, CancellationToken.None), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } [Fact] public async Task WithIndexNameAndCancellationToken_DropsIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act await Sut.DropIndexAsync(expectedIndexName, cancellationToken: token); // Assert indexManger.Verify(x => x.DropOneAsync(expectedIndexName, token), Times.Once); } [Fact] public async Task WithIndexNameAndPartitionKeyAndCancellationToken_DropsIndex() { // Arrange var expectedIndexName = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var partitionKey = Fixture.Create(); var context = SetupContext(collection); var indexManger = SetupIndexManager(collection, expectedIndexName); // Act await Sut.DropIndexAsync(expectedIndexName, partitionKey, token); // Assert indexManger.Verify(x => x.DropOneAsync(expectedIndexName, token), Times.Once); context.Verify(x => x.GetCollection(partitionKey), Times.Once); } private Mock SetupContext(Mock> collection) { var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); return context; } private Mock> SetupIndexManager(Mock> collection, string indexName) { var indexManager = MockOf>(); indexManager .Setup( x => x.CreateOneAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(indexName); collection .SetupGet(x => x.Indexes) .Returns(indexManager.Object); return indexManager; } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbIndexHandlerTests/GetIndexNamesAsyncTests.cs ================================================ using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Bson; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests; public class GetIndexNamesAsyncTests : BaseIndexTests { [Fact] public async Task WithNoParameters_ReturnsAllIndexNames() { // Arrange var indexNames = Fixture.CreateMany().ToList(); var indexes = indexNames.Select(x => new BsonDocument {{"name", x}}).ToList(); var collection = MockOf>(); var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); var (cursor, manager) = SetupIndexes(indexes, collection); // Act var result = await Sut.GetIndexesNamesAsync(); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(indexNames); context.Verify(x => x.GetCollection(null)); manager.Verify(x => x.ListAsync(CancellationToken.None)); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None)); } [Fact] public async Task WithPartitionKey_ReturnsAllIndexNames() { // Arrange var partitionKey = Fixture.Create(); var indexNames = Fixture.CreateMany().ToList(); var indexes = indexNames.Select(x => new BsonDocument {{"name", x}}).ToList(); var collection = MockOf>(); var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); var (cursor, manager) = SetupIndexes(indexes, collection); // Act var result = await Sut.GetIndexesNamesAsync(partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(indexNames); context.Verify(x => x.GetCollection(partitionKey)); manager.Verify(x => x.ListAsync(CancellationToken.None)); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None)); } [Fact] public async Task WithCancellationToken_ReturnsAllIndexNames() { // Arrange var token = new CancellationToken(); var indexNames = Fixture.CreateMany().ToList(); var indexes = indexNames.Select(x => new BsonDocument {{"name", x}}).ToList(); var collection = MockOf>(); var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); var (cursor, manager) = SetupIndexes(indexes, collection); // Act var result = await Sut.GetIndexesNamesAsync(cancellationToken:token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(indexNames); context.Verify(x => x.GetCollection(null)); manager.Verify(x => x.ListAsync(token)); cursor.Verify(x => x.MoveNextAsync(token)); } [Fact] public async Task WithPartitionKeyCancellationToken_ReturnsAllIndexNames() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(); var indexNames = Fixture.CreateMany().ToList(); var indexes = indexNames.Select(x => new BsonDocument {{"name", x}}).ToList(); var collection = MockOf>(); var context = MockOf(); context .Setup(x => x.GetCollection(It.IsAny())) .Returns(collection.Object); var (cursor, manager) = SetupIndexes(indexes, collection); // Act var result = await Sut.GetIndexesNamesAsync(partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(indexNames); context.Verify(x => x.GetCollection(partitionKey)); manager.Verify(x => x.ListAsync(token)); cursor.Verify(x => x.MoveNextAsync(token)); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/AnyAsyncTests.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class AnyAsyncTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; [Fact] public async Task WithFilter_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.AnyAsync(filter); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocumentsAsync(It.Is>(y => y.Expression == filter), null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.AnyAsync(filter, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocumentsAsync(It.Is>(y => y.Expression == filter), null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterAndPartitionKey_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.AnyAsync(filter, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocumentsAsync(It.Is>(y => y.Expression == filter), null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.AnyAsync(filter, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocumentsAsync(It.Is>(y => y.Expression == filter), null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithCondition_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.AnyAsync(condition); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocumentsAsync(condition, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithConditionAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.AnyAsync(condition, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocumentsAsync(condition, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithConditionAndPartitionKey_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.AnyAsync(condition, partitionKey: partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocumentsAsync(condition, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithConditionAndPartitionKeyAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.AnyAsync(condition, partitionKey: partitionKey, cancellationToken:token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocumentsAsync(condition, null, token), Times.Once); result.Should().BeTrue(); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/AnyTests.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class AnyTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; [Fact] public void WithFilter_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Any(filter); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocuments(It.Is>(y => y.Expression == filter), null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Any(filter, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocuments(It.Is>(y => y.Expression == filter), null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterAndPartitionKey_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Any(filter, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocuments(It.Is>(y => y.Expression == filter), null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Any(filter, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocuments(It.Is>(y => y.Expression == filter), null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithCondition_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Any(condition); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocuments(condition, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithConditionAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Any(condition, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocuments(condition, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithConditionAndPartitionKey_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Any(condition, partitionKey: partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocuments(condition, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithConditionAndPartitionKeyAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Any(condition, partitionKey: partitionKey, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocuments(condition, null, token), Times.Once); result.Should().BeTrue(); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/BaseReaderTests.cs ================================================ using System.Collections.Generic; using System.Threading; using CoreUnitTests.Infrastructure; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class BaseReaderTests : GenericTestContext { protected Mock> SetupSyncCursor(List documents) { var asyncCursor = MockOf>(); var moveNextSequence = asyncCursor .SetupSequence(x => x.MoveNext(It.IsAny())); var currentSequence = asyncCursor .SetupSequence(x => x.Current); foreach (var projection in documents) { moveNextSequence.Returns(true); currentSequence.Returns(new[] {projection}); } moveNextSequence.Returns(false); return asyncCursor; } protected Mock> SetupAsyncCursor(List documents) { var asyncCursor = MockOf>(); var moveNextSequence = asyncCursor .SetupSequence(x => x.MoveNextAsync(It.IsAny())); var currentSequence = asyncCursor .SetupSequence(x => x.Current); foreach (var projection in documents) { moveNextSequence.ReturnsAsync(true); currentSequence.Returns(new[] {projection}); } moveNextSequence.ReturnsAsync(false); return asyncCursor; } protected static void SetupFindAsync(Mock> collection, Mock> asyncCursor) => collection .Setup( x => x.FindAsync( It.IsAny>(), It.IsAny>(), It.IsAny())) .ReturnsAsync(asyncCursor.Object); protected static void SetupFindSync(Mock> collection, Mock> asyncCursor) => collection .Setup( x => x.FindSync( It.IsAny>(), It.IsAny>(), It.IsAny())) .Returns(asyncCursor.Object); } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/CountAsyncTests.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class CountAsyncTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; [Fact] public async Task WithFilter_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.CountAsync(filter); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocumentsAsync(It.Is>(y => y.Expression == filter), null, CancellationToken.None), Times.Once); result.Should().Be(documents.Count); } [Fact] public async Task WithFilterAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.CountAsync(filter, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocumentsAsync(It.Is>(y => y.Expression == filter), null, token), Times.Once); result.Should().Be(documents.Count); } [Fact] public async Task WithFilterAndPartitionKey_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.CountAsync(filter, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocumentsAsync(It.Is>(y => y.Expression == filter), null, CancellationToken.None), Times.Once); result.Should().Be(documents.Count); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.CountAsync(filter, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocumentsAsync(It.Is>(y => y.Expression == filter), null, token), Times.Once); result.Should().Be(documents.Count); } [Fact] public async Task WithCondition_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.CountAsync(condition); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocumentsAsync(condition, null, CancellationToken.None), Times.Once); result.Should().Be(documents.Count); } [Fact] public async Task WithConditionAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.CountAsync(condition, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocumentsAsync(condition, null, token), Times.Once); result.Should().Be(documents.Count); } [Fact] public async Task WithConditionAndPartitionKey_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.CountAsync(condition, partitionKey: partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocumentsAsync(condition, null, CancellationToken.None), Times.Once); result.Should().Be(documents.Count); } [Fact] public async Task WithConditionAndPartitionKeyAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocumentsAsync( It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents.Count); // Act var result = await Sut.CountAsync(condition, partitionKey: partitionKey, cancellationToken:token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocumentsAsync(condition, null, token), Times.Once); result.Should().Be(documents.Count); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/CountTests.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class CountTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; [Fact] public void WithFilter_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Count(filter); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocuments(It.Is>(y => y.Expression == filter), It.IsAny(), CancellationToken.None), Times.Once); result.Should().Be(documents.Count); } [Fact] public void WithFilterAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Count(filter, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocuments(It.Is>(y => y.Expression == filter), It.IsAny(), token), Times.Once); result.Should().Be(documents.Count); } [Fact] public void WithFilterAndPartitionKey_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Count(filter, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocuments(It.Is>(y => y.Expression == filter), It.IsAny(), CancellationToken.None), Times.Once); result.Should().Be(documents.Count); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Count(filter, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocuments(It.Is>(y => y.Expression == filter), It.IsAny(), token), Times.Once); result.Should().Be(documents.Count); } [Fact] public void WithCondition_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Count(condition); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocuments(condition, null, CancellationToken.None), Times.Once); result.Should().Be(documents.Count); } [Fact] public void WithConditionAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(null)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Count(condition, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); collection.Verify( x => x.CountDocuments(condition, null, token), Times.Once); result.Should().Be(documents.Count); } [Fact] public void WithConditionAndPartitionKey_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Count(condition, partitionKey: partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocuments(condition, null, CancellationToken.None), Times.Once); result.Should().Be(documents.Count); } [Fact] public void WithConditionAndPartitionKeyAndCancellationToken_ReturnsResult() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); collection .Setup( x => x.CountDocuments( It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(documents.Count); // Act var result = Sut.Count(condition, partitionKey: partitionKey, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); collection.Verify( x => x.CountDocuments(condition, null, token), Times.Once); result.Should().Be(documents.Count); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetAllAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetAllAsyncTests : BaseReaderTests { [Fact] public async Task WithFilter_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetAllAsync(filter); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithFilterAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(false); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetAllAsync(filter, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithFilterAndPartitionKey_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetAllAsync(filter, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(false); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetAllAsync(filter, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithCondition_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetAllAsync(condition); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithConditionAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(false); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetAllAsync(condition, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithConditionAndPartitionKey_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetAllAsync(condition, partitionKey: partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1)); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithConditionAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var token = new CancellationToken(false); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetAllAsync(condition, partitionKey: partitionKey, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithConditionAndFindOptions_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetAllAsync(condition, options); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithConditionAndFindOptionsAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(false); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetAllAsync(condition, options, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public async Task WithConditionAndFindOptionsAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(false); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetAllAsync(condition, options, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } private (Mock, Mock>) SetupAsyncGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupAsyncCursor(documents); SetupFindAsync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetAllTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetAllTests : BaseReaderTests { [Fact] public void WithFilter_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupGet(documents, collection); // Act var result = Sut.GetAll(filter); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithFilterAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(false); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupGet(documents, collection); // Act var result = Sut.GetAll(filter, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithFilterAndPartitionKey_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupGet(documents, collection, partitionKey); // Act var result = Sut.GetAll(filter, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(false); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupGet(documents, collection, partitionKey); // Act var result = Sut.GetAll(filter, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithCondition_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var (context, cursor) = SetupGet(documents, collection); // Act var result = Sut.GetAll(condition); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithConditionAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(false); var (context, cursor) = SetupGet(documents, collection); // Act var result = Sut.GetAll(condition, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithConditionAndPartitionKey_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var (context, cursor) = SetupGet(documents, collection, partitionKey); // Act var result = Sut.GetAll(condition, partitionKey: partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1)); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithConditionAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var token = new CancellationToken(false); var (context, cursor) = SetupGet(documents, collection, partitionKey); // Act var result = Sut.GetAll(condition, partitionKey: partitionKey, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithConditionAndFindOptions_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var (context, cursor) = SetupGet(documents, collection); // Act var result = Sut.GetAll(condition, options); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithConditionAndFindOptionsAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(false); var (context, cursor) = SetupGet(documents, collection); // Act var result = Sut.GetAll(condition, options, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } [Fact] public void WithConditionAndFindOptionsAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(false); var partitionKey = Fixture.Create(); var (context, cursor) = SetupGet(documents, collection, partitionKey); // Act var result = Sut.GetAll(condition, options, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Exactly(documents.Count)); cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => documents.Contains(x)); } private (Mock, Mock>) SetupGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupSyncCursor(documents); SetupFindSync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetByIdAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetByIdAsyncTests : BaseReaderTests { [Fact] public async Task WithId_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetByIdAsync(documents[0].Id); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithIdAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetByIdAsync(documents[0].Id, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithIdAndPartitionKey_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetByIdAsync(documents[0].Id, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithIdAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetByIdAsync(documents[0].Id, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } private (Mock, Mock>) SetupAsyncGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupAsyncCursor(documents); SetupFindAsync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetByIdTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetByIdTests : BaseReaderTests { [Fact] public void WithId_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = Sut.GetById(documents[0].Id); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithIdAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = Sut.GetById(documents[0].Id, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithIdAndPartitionKey_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = Sut.GetById(documents[0].Id, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithIdAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = Sut.GetById(documents[0].Id, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } private (Mock, Mock>) SetupAsyncGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupSyncCursor(documents); SetupFindSync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetByMaxAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetByMaxAsyncTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; private readonly Expression> selector = x => x.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetByMaxAsync(filter, selector); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetByMaxAsync(filter, selector, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetByMaxAsync(filter, selector, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetByMaxAsync(filter, selector, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } private (Mock, Mock>) SetupAsyncGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupAsyncCursor(documents); SetupFindAsync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetByMaxTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetByMaxTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; private readonly Expression> selector = x => x.SomeValue; [Fact] public void WithFilterAndSelector_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetByMax(filter, selector); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetByMax(filter, selector, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupSyncGet(documents, collection, partitionKey); // Act var result = Sut.GetByMax(filter, selector, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(documents, collection, partitionKey); // Act var result = Sut.GetByMax(filter, selector, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } private (Mock, Mock>) SetupSyncGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupSyncCursor(documents); SetupFindSync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetByMinAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetByMinAsyncTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; private readonly Expression> selector = x => x.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetByMinAsync(filter, selector); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetByMinAsync(filter, selector, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetByMinAsync(filter, selector, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetByMinAsync(filter, selector, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } private (Mock, Mock>) SetupAsyncGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupAsyncCursor(documents); SetupFindAsync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetByMinTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetByMinTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; private readonly Expression> selector = x => x.SomeValue; [Fact] public void WithFilterAndSelector_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetByMin(filter, selector); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetByMin(filter, selector, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupSyncGet(documents, collection, partitionKey); // Act var result = Sut.GetByMin(filter, selector, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(documents, collection, partitionKey); // Act var result = Sut.GetByMin(filter, selector, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } private (Mock, Mock>) SetupSyncGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupSyncCursor(documents); SetupFindSync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetMaxValueAsyncTests .cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetMaxValueAsyncTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; private readonly Expression> selector = x => x.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var (context, cursor) = SetupAsyncGet(value, collection); // Act var result = await Sut.GetMaxValueAsync(filter, selector); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().Be(value); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(value, collection); // Act var result = await Sut.GetMaxValueAsync(filter, selector, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().Be(value); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(value, collection, partitionKey); // Act var result = await Sut.GetMaxValueAsync(filter, selector, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().Be(value); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(value, collection, partitionKey); // Act var result = await Sut.GetMaxValueAsync(filter, selector, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().Be(value); } private (Mock, Mock>) SetupAsyncGet( TValue result, Mock> collection, string partitionKey = null) { var asyncCursor = SetupAsyncCursor(new List {result}); SetupFindAsync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetMaxValueTests .cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetMaxValueTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; private readonly Expression> selector = x => x.SomeValue; [Fact] public void WithFilterAndSelector_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var (context, cursor) = SetupSyncGet(value, collection); // Act var result = Sut.GetMaxValue(filter, selector); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().Be(value); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(value, collection); // Act var result = Sut.GetMaxValue(filter, selector, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().Be(value); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupSyncGet(value, collection, partitionKey); // Act var result = Sut.GetMaxValue(filter, selector, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().Be(value); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(value, collection, partitionKey); // Act var result = Sut.GetMaxValue(filter, selector, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().Be(value); } private (Mock, Mock>) SetupSyncGet( TValue result, Mock> collection, string partitionKey = null) { var asyncCursor = SetupSyncCursor(new List {result}); SetupFindSync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetMinValueAsyncTests .cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetMinValueAsyncTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; private readonly Expression> selector = x => x.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var (context, cursor) = SetupAsyncGet(value, collection); // Act var result = await Sut.GetMinValueAsync(filter, selector); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().Be(value); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(value, collection); // Act var result = await Sut.GetMinValueAsync(filter, selector, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().Be(value); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(value, collection, partitionKey); // Act var result = await Sut.GetMinValueAsync(filter, selector, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().Be(value); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(value, collection, partitionKey); // Act var result = await Sut.GetMinValueAsync(filter, selector, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().Be(value); } private (Mock, Mock>) SetupAsyncGet( TValue result, Mock> collection, string partitionKey = null) { var asyncCursor = SetupAsyncCursor(new List {result}); SetupFindAsync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetMinValueTests .cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetMinValueTests : BaseReaderTests { private readonly Expression> filter = x => x.SomeContent == "SomeContent"; private readonly Expression> selector = x => x.SomeValue; [Fact] public void WithFilterAndSelector_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var (context, cursor) = SetupSyncGet(value, collection); // Act var result = Sut.GetMinValue(filter, selector); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().Be(value); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(value, collection); // Act var result = Sut.GetMinValue(filter, selector, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().Be(value); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupSyncGet(value, collection, partitionKey); // Act var result = Sut.GetMinValue(filter, selector, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().Be(value); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument() { // Arrange var value = Fixture.Create(); var collection = MockOf>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(value, collection, partitionKey); // Act var result = Sut.GetMinValue(filter, selector, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().Be(value); } private (Mock, Mock>) SetupSyncGet( TValue result, Mock> collection, string partitionKey = null) { var asyncCursor = SetupSyncCursor(new List {result}); SetupFindSync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetOneAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetOneAsyncTests : BaseReaderTests { [Fact] public async Task WithFilter_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetOneAsync(filter); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithFilterAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetOneAsync(filter, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithFilterAndPartitionKey_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetOneAsync(filter, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetOneAsync(filter, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithCondition_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetOneAsync(condition); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithConditionAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetOneAsync(condition, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithConditionAndPartitionKey_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetOneAsync(condition, partitionKey: partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); cursor.Verify(x => x.Current, Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithConditionAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetOneAsync(condition, partitionKey: partitionKey, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithConditionAndFindOptions_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetOneAsync(condition, options); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithConditionAndFindOptionsAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncGet(documents, collection); // Act var result = await Sut.GetOneAsync(condition, options, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public async Task WithConditionAndFindOptionsAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey); // Act var result = await Sut.GetOneAsync(condition, options, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } private (Mock, Mock>) SetupAsyncGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupAsyncCursor(documents); SetupFindAsync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/GetOneTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class GetOneTests : BaseReaderTests { [Fact] public void WithFilter_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetOne(filter); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); cursor.Verify(x => x.Current, Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithFilterAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetOne(filter, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithFilterAndPartitionKey_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupSyncGet(documents, collection, partitionKey); // Act var result = Sut.GetOne(filter, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression> filter = x => x.Id == documents[0].Id; var (context, cursor) = SetupSyncGet(documents, collection, partitionKey); // Act var result = Sut.GetOne(filter, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithCondition_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetOne(condition); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithConditionAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetOne(condition, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithConditionAndPartitionKey_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var (context, cursor) = SetupSyncGet(documents, collection, partitionKey); // Act var result = Sut.GetOne(condition, partitionKey: partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); cursor.Verify(x => x.Current, Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithConditionAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(documents, collection, partitionKey); // Act var result = Sut.GetOne(condition, partitionKey: partitionKey, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithConditionAndFindOptions_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetOne(condition, options); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithConditionAndFindOptionsAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var (context, cursor) = SetupSyncGet(documents, collection); // Act var result = Sut.GetOne(condition, options, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } [Fact] public void WithConditionAndFindOptionsAndPartitionKeyAndCancellationToken_GetsMatchingDocuments() { // Arrange var collection = MockOf>(); var documents = Fixture.CreateMany().ToList(); var options = Fixture .Build() .Without(x => x.Comment) .Without(x => x.Hint) .Create(); var condition = Builders.Filter.Eq("Id", documents[0].Id); var token = new CancellationToken(true); var partitionKey = Fixture.Create(); var (context, cursor) = SetupSyncGet(documents, collection, partitionKey); // Act var result = Sut.GetOne(condition, options, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(documents[0]); } private (Mock, Mock>) SetupSyncGet( List documents, Mock> collection, string partitionKey = null) { var asyncCursor = SetupSyncCursor(documents); SetupFindSync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/ProjectManyAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class ProjectManyAsyncTests : BaseReaderTests { private readonly Expression> filter = t => string.IsNullOrWhiteSpace(t.SomeContent2); private readonly Expression> projectionExpression = t => new TestProjection {TestDocumentId = t.Id, NestedData = t.Nested.SomeDate}; [Fact] public async Task WithFilterAndProjection_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var (context, cursor) = SetupAsyncProjection(projections, collection); // Act var result = await Sut.ProjectManyAsync(filter, projectionExpression); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.AtLeast(1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => projections.Contains(x)); } [Fact] public async Task WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(false); var (context, cursor) = SetupAsyncProjection(projections, collection); // Act var result = await Sut.ProjectManyAsync(filter, projectionExpression, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.AtLeast(1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => projections.Contains(x)); } [Fact] public async Task WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey); // Act var result = await Sut.ProjectManyAsync(filter, projectionExpression, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.AtLeast(1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => projections.Contains(x)); } [Fact] public async Task WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(false); var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey); // Act var result = await Sut.ProjectManyAsync(filter, projectionExpression, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.AtLeast(1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => projections.Contains(x)); } private (Mock, Mock>) SetupAsyncProjection( List projections, Mock> collection, string partitionKey = null) { var asyncCursor = SetupAsyncCursor(projections); collection .Setup( x => x.FindAsync( It.IsAny>(), It.IsAny>(), It.IsAny())) .ReturnsAsync(asyncCursor.Object); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/ProjectManyTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class ProjectManyTests : BaseReaderTests { private readonly Expression> filter = t => string.IsNullOrWhiteSpace(t.SomeContent2); private readonly Expression> projectionExpression = t => new TestProjection {TestDocumentId = t.Id, NestedData = t.Nested.SomeDate}; [Fact] public void WithFilterAndProjection_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var (context, cursor) = SetupAsyncProjection(projections, collection); // Act var result = Sut.ProjectMany(filter, projectionExpression); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.AtLeast(1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => projections.Contains(x)); } [Fact] public void WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(false); var (context, cursor) = SetupAsyncProjection(projections, collection); // Act var result = Sut.ProjectMany(filter, projectionExpression, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.MoveNext(token), Times.AtLeast(1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => projections.Contains(x)); } [Fact] public void WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey); // Act var result = Sut.ProjectMany(filter, projectionExpression, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.AtLeast(1)); result.Should().NotBeNull(); result.Should().OnlyContain(x => projections.Contains(x)); } [Fact] public void WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(false); var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey); // Act var result = Sut.ProjectMany(filter, projectionExpression, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.MoveNext(token), Times.AtLeast(projections.Count)); result.Should().NotBeNull(); result.Should().OnlyContain(x => projections.Contains(x)); } private (Mock, Mock>) SetupAsyncProjection( List projections, Mock> collection, string partitionKey = null) { var asyncCursor = SetupSyncCursor(projections); SetupFindSync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/ProjectOneAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class ProjectOneAsyncTests : BaseReaderTests { private readonly Expression> filter = t => string.IsNullOrWhiteSpace(t.SomeContent2); private readonly Expression> projectionExpression = t => new TestProjection {TestDocumentId = t.Id, NestedData = t.Nested.SomeDate}; [Fact] public async Task WithFilterAndProjection_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var (context, cursor) = SetupAsyncProjection(projections, collection); // Act var result = await Sut.ProjectOneAsync(filter, projectionExpression); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(projections[0]); } [Fact] public async Task WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncProjection(projections, collection); // Act var result = await Sut.ProjectOneAsync(filter, projectionExpression, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(projections[0]); } [Fact] public async Task WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey); // Act var result = await Sut.ProjectOneAsync(filter, projectionExpression, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(projections[0]); } [Fact] public async Task WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey); // Act var result = await Sut.ProjectOneAsync(filter, projectionExpression, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNextAsync(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(projections[0]); } private (Mock, Mock>) SetupAsyncProjection( List projections, Mock> collection, string partitionKey = null) { var asyncCursor = SetupAsyncCursor(projections); SetupFindAsync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbReaderTests/ProjectOneTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests; public class ProjectOneTests : BaseReaderTests { private readonly Expression> filter = t => string.IsNullOrWhiteSpace(t.SomeContent2); private readonly Expression> projectionExpression = t => new TestProjection {TestDocumentId = t.Id, NestedData = t.Nested.SomeDate}; [Fact] public void WithFilterAndProjection_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var (context, cursor) = SetupProjection(projections, collection); // Act var result = Sut.ProjectOne(filter, projectionExpression); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(projections[0]); } [Fact] public void WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); var (context, cursor) = SetupProjection(projections, collection); // Act var result = Sut.ProjectOne(filter, projectionExpression, cancellationToken: token); // Assert context.Verify(x => x.GetCollection(null), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(projections[0]); } [Fact] public void WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var (context, cursor) = SetupProjection(projections, collection, partitionKey); // Act var result = Sut.ProjectOne(filter, projectionExpression, partitionKey); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once); result.Should().NotBeNull(); result.Should().Be(projections[0]); } [Fact] public void WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var collection = MockOf>(); var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var (context, cursor) = SetupProjection(projections, collection, partitionKey); // Act var result = Sut.ProjectOne(filter, projectionExpression, partitionKey, token); // Assert context.Verify(x => x.GetCollection(partitionKey), Times.Once); cursor.Verify(x => x.Current, Times.Once); cursor.Verify(x => x.MoveNext(token), Times.Once); result.Should().NotBeNull(); result.Should().Be(projections[0]); } private (Mock, Mock>) SetupProjection( List projections, Mock> collection, string partitionKey = null) { var asyncCursor = SetupSyncCursor(projections); SetupFindSync(collection, asyncCursor); var context = MockOf(); context .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return (context, asyncCursor); } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbUpdaterTests/UpdateManyAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Bson; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbUpdaterTests; public class UpdateManyAsyncTests : GenericTestContext { [Fact] public async Task WithFilterAndUpdateDefinition_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); // Act var result = await Sut.UpdateManyAsync( filter, updateDefinition); // Assert result.Should().Be(count); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(updateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterAndUpdateDefinitionAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); var token = new CancellationToken(true); // Act var result = await Sut.UpdateManyAsync( filter, updateDefinition, cancellationToken: token); // Assert result.Should().Be(count); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(updateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterAndUpdateDefinitionAndPartitionKey_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count, partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); // Act var result = await Sut.UpdateManyAsync( filter, updateDefinition, partitionKey); // Assert result.Should().Be(count); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(updateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterAndUpdateDefinitionAndPartitionKeyAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count, partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); var token = new CancellationToken(true); // Act var result = await Sut.UpdateManyAsync( filter, updateDefinition, partitionKey, cancellationToken: token); // Assert result.Should().Be(count); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(updateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterAndFieldExpressionAndValue_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(count); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateManyAsync( filter, fieldExpression, value); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterAndFieldExpressionAndValueAndPartitionKey_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(count, partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateManyAsync( filter, fieldExpression, value, partitionKey); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterAndFieldExpressionAndValueAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(count); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateManyAsync( filter, fieldExpression, value, cancellationToken: token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(count, partitionKey); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateManyAsync( filter, fieldExpression, value, partitionKey, token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValue_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(count); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateManyAsync( filterExpression, fieldExpression, value); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(count); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateManyAsync( filterExpression, fieldExpression, value, cancellationToken: token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_UpdatesMany() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var count = Fixture.Create(); var collection = SetupCollection(count, partitionKey); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateManyAsync( filterExpression, fieldExpression, value, partitionKey); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_UpdatesMany() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(count, partitionKey); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateManyAsync( filterExpression, fieldExpression, value, partitionKey, token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterExpressionAndUpdateDefinition_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; // Act var result = await Sut.UpdateManyAsync( filterExpression, updateDefinition); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterExpressionAndUpdateDefinitionAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; // Act var result = await Sut.UpdateManyAsync( filterExpression, updateDefinition, cancellationToken: token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterExpressionAndUpdateDefinitionAndPartitionKey_UpdatesMany() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var count = Fixture.Create(); var collection = SetupCollection(count, partitionKey); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; // Act var result = await Sut.UpdateManyAsync( filterExpression, updateDefinition, partitionKey); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_UpdatesMany() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var partitionKey = Fixture.Create(); var collection = SetupCollection(count, partitionKey); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; // Act var result = await Sut.UpdateManyAsync( filterExpression, updateDefinition, partitionKey, token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateManyAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } private Mock> SetupCollection(long count, string partitionKey = null) { var replacedId = Fixture.Create(); var replaceResult = new ReplaceOneResult.Acknowledged(count, count, new BsonBinaryData(replacedId, GuidRepresentation.Standard)); var updateResult = new UpdateResult.Acknowledged(count, count, new BsonBinaryData(replacedId, GuidRepresentation.Standard)); var collection = MockOf>(); collection .Setup( x => x.ReplaceOneAsync( It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(replaceResult); collection .Setup( x => x.UpdateManyAsync( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(updateResult); collection .Setup( x => x.ReplaceOneAsync( It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(replaceResult); collection .Setup( x => x.UpdateManyAsync( It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(updateResult); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return collection; } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbUpdaterTests/UpdateManyTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Bson; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbUpdaterTests; public class UpdateManyTests : GenericTestContext { [Fact] public void WithFilterAndUpdateDefinition_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); // Act var result = Sut.UpdateMany( filter, updateDefinition); // Assert result.Should().Be(count); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(updateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterAndUpdateDefinitionAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); var token = new CancellationToken(true); // Act var result = Sut.UpdateMany( filter, updateDefinition, cancellationToken: token); // Assert result.Should().Be(count); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(updateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterAndUpdateDefinitionAndPartitionKey_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count, partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); // Act var result = Sut.UpdateMany( filter, updateDefinition, partitionKey); // Assert result.Should().Be(count); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(updateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterAndUpdateDefinitionAndPartitionKeyAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count, partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); var token = new CancellationToken(true); // Act var result = Sut.UpdateMany( filter, updateDefinition, partitionKey, token); // Assert result.Should().Be(count); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(updateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterAndFieldExpressionAndValue_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(count); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateMany( filter, fieldExpression, value); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterAndFieldExpressionAndValueAndPartitionKey_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(count, partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateMany( filter, fieldExpression, value, partitionKey); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterAndFieldExpressionAndValueAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(count); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateMany( filter, fieldExpression, value, cancellationToken: token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(count, partitionKey); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateMany( filter, fieldExpression, value, partitionKey, token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValue_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(count); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateMany( filterExpression, fieldExpression, value); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(count); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateMany( filterExpression, fieldExpression, value, cancellationToken: token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_UpdatesMany() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var count = Fixture.Create(); var collection = SetupCollection(count, partitionKey); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateMany( filterExpression, fieldExpression, value, partitionKey); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_UpdatesMany() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(count, partitionKey); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateMany( filterExpression, fieldExpression, value, partitionKey, token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterExpressionAndUpdateDefinition_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; // Act var result = Sut.UpdateMany( filterExpression, updateDefinition); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterExpressionAndUpdateDefinitionAndCancellationToken_UpdatesMany() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var collection = SetupCollection(count); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; // Act var result = Sut.UpdateMany( filterExpression, updateDefinition, cancellationToken: token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterExpressionAndUpdateDefinitionAndPartitionKey_UpdatesMany() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var count = Fixture.Create(); var collection = SetupCollection(count, partitionKey); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; // Act var result = Sut.UpdateMany( filterExpression, updateDefinition, partitionKey); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_UpdatesMany() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); var updateDefinition = Builders.Update.Set(x => x.SomeContent, value); var partitionKey = Fixture.Create(); var collection = SetupCollection(count, partitionKey); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; // Act var result = Sut.UpdateMany( filterExpression, updateDefinition, partitionKey, token); // Assert result.Should().Be(count); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateMany( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } private Mock> SetupCollection(long count, string partitionKey = null) { var replacedId = Fixture.Create(); var replaceResult = new ReplaceOneResult.Acknowledged(count, count, new BsonBinaryData(replacedId, GuidRepresentation.Standard)); var updateResult = new UpdateResult.Acknowledged(count, count, new BsonBinaryData(replacedId, GuidRepresentation.Standard)); var collection = MockOf>(); collection .Setup( x => x.ReplaceOneAsync( It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(replaceResult); collection .Setup( x => x.UpdateMany( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(updateResult); collection .Setup( x => x.ReplaceOneAsync( It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(replaceResult); collection .Setup( x => x.UpdateMany( It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(updateResult); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return collection; } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbUpdaterTests/UpdateOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Bson; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbUpdaterTests; public class UpdateOneAsyncTests : GenericTestContext { [Fact] public async Task WithDocument_ReplacesOne() { // Arrange var document = Fixture.Create(); var collection = SetupCollection(); // Act var result = await Sut.UpdateOneAsync(document); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); ReplaceOptions expectedOptions = null; collection .Verify( x => x.ReplaceOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), document, expectedOptions, CancellationToken.None), Times.Once()); } [Fact] public async Task WithDocumentAndCancellationToken_ReplacesOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); var collection = SetupCollection(); // Act var result = await Sut.UpdateOneAsync(document, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); ReplaceOptions expectedOptions = null; collection .Verify( x => x.ReplaceOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), document, expectedOptions, token), Times.Once()); } [Fact] public async Task WithDocumentAndUpdateDefinition_ReplacesOne() { // Arrange var document = Fixture.Create(); var collection = SetupCollection(); var updateDefinition = Builders.Update.Set(x => x.Id, document.Id); // Act var result = await Sut.UpdateOneAsync(document, updateDefinition); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), updateDefinition, null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithDocumentAndUpdateDefinitionAndCancellationToken_ReplacesOne() { // Arrange var document = Fixture.Create(); var collection = SetupCollection(); var updateDefinition = Builders.Update.Set(x => x.Id, document.Id); var token = new CancellationToken(true); // Act var result = await Sut.UpdateOneAsync(document, updateDefinition, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), updateDefinition, null, token), Times.Once()); } [Fact] public async Task WithDocumentAndFieldExpressionAndValue_ReplacesOne() { // Arrange var document = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync(document, fieldExpression, value); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithDocumentAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var document = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync(document, fieldExpression, value, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterAndFieldExpressionAndValueAndPartitionKey_ReplacesOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( filter, fieldExpression, value, partitionKey); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( filter, fieldExpression, value, cancellationToken: token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( filter, fieldExpression, value, partitionKey, token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( filterExpression, fieldExpression, value, cancellationToken: token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ReplacesOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( filterExpression, fieldExpression, value, partitionKey); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( filterExpression, fieldExpression, value, partitionKey, token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOneAsync( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithClientSessionAndDocument_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var collection = SetupCollection(); // Act var result = await Sut.UpdateOneAsync(session.Object, document); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); ReplaceOptions expectedOptions = null; collection .Verify( x => x.ReplaceOneAsync( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), document, expectedOptions, CancellationToken.None), Times.Once()); } [Fact] public async Task WithClientSessionAndDocumentAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var token = new CancellationToken(true); var collection = SetupCollection(); // Act var result = await Sut.UpdateOneAsync(session.Object, document, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); ReplaceOptions expectedOptions = null; collection .Verify( x => x.ReplaceOneAsync( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), document, expectedOptions, token), Times.Once()); } [Fact] public async Task WithClientSessionAndDocumentAndUpdateDefinition_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var collection = SetupCollection(); var updateDefinition = Builders.Update.Set(x => x.Id, document.Id); // Act var result = await Sut.UpdateOneAsync(session.Object, document, updateDefinition); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), updateDefinition, null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithClientSessionAndDocumentAndUpdateDefinitionAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var collection = SetupCollection(); var updateDefinition = Builders.Update.Set(x => x.Id, document.Id); var token = new CancellationToken(true); // Act var result = await Sut.UpdateOneAsync(session.Object, document, updateDefinition, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), updateDefinition, null, token), Times.Once()); } [Fact] public async Task WithClientSessionAndDocumentAndFieldExpressionAndValue_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync(session.Object, document, fieldExpression, value); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithClientSessionAndDocumentAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync(session.Object, document, fieldExpression, value, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithClientSessionAndFilterAndFieldExpressionAndValueAndPartitionKey_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( session.Object, filter, fieldExpression, value, partitionKey); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithClientSessionAndFilterAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( session.Object, filter, fieldExpression, value, cancellationToken: token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithClientSessionAndFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( session.Object, filter, fieldExpression, value, partitionKey, token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( session.Object, filterExpression, fieldExpression, value, cancellationToken: token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public async Task WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( session.Object, filterExpression, fieldExpression, value, partitionKey); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = await Sut.UpdateOneAsync( session.Object, filterExpression, fieldExpression, value, partitionKey, token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOneAsync( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } private Mock> SetupCollection(string partitionKey = null) { var replacedId = Fixture.Create(); var count = Fixture.Create(); var replaceResult = new ReplaceOneResult.Acknowledged(count, 1, new BsonBinaryData(replacedId, GuidRepresentation.Standard)); var updateResult = new UpdateResult.Acknowledged(count, 1, new BsonBinaryData(replacedId, GuidRepresentation.Standard)); var collection = MockOf>(); collection .Setup( x => x.ReplaceOneAsync( It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(replaceResult); collection .Setup( x => x.UpdateOneAsync( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(updateResult); collection .Setup( x => x.ReplaceOneAsync( It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(replaceResult); collection .Setup( x => x.UpdateOneAsync( It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(updateResult); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return collection; } } ================================================ FILE: CoreUnitTests/DataAccessTests/MongoDbUpdaterTests/UpdateOneTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Bson; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.DataAccessTests.MongoDbUpdaterTests; public class UpdateOneTests : GenericTestContext { [Fact] public void WithDocument_ReplacesOne() { // Arrange var document = Fixture.Create(); var collection = SetupCollection(); // Act var result = Sut.UpdateOne(document); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); ReplaceOptions expectedOptions = null; collection .Verify( x => x.ReplaceOne( It.Is>(f => f.EquivalentTo(expectedFilter)), document, expectedOptions, CancellationToken.None), Times.Once()); } [Fact] public void WithDocumentAndCancellationToken_ReplacesOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); var collection = SetupCollection(); // Act var result = Sut.UpdateOne(document, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); ReplaceOptions expectedOptions = null; collection .Verify( x => x.ReplaceOne( It.Is>(f => f.EquivalentTo(expectedFilter)), document, expectedOptions, token), Times.Once()); } [Fact] public void WithDocumentAndUpdateDefinition_ReplacesOne() { // Arrange var document = Fixture.Create(); var collection = SetupCollection(); var updateDefinition = Builders.Update.Set(x => x.Id, document.Id); // Act var result = Sut.UpdateOne(document, updateDefinition); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(expectedFilter)), updateDefinition, null, CancellationToken.None), Times.Once()); } [Fact] public void WithDocumentAndUpdateDefinitionAndCancellationToken_ReplacesOne() { // Arrange var document = Fixture.Create(); var collection = SetupCollection(); var updateDefinition = Builders.Update.Set(x => x.Id, document.Id); var token = new CancellationToken(true); // Act var result = Sut.UpdateOne(document, updateDefinition, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(expectedFilter)), updateDefinition, null, token), Times.Once()); } [Fact] public void WithDocumentAndFieldExpressionAndValue_ReplacesOne() { // Arrange var document = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne(document, fieldExpression, value); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithDocumentAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var document = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne(document, fieldExpression, value, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterAndFieldExpressionAndValueAndPartitionKey_ReplacesOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( filter, fieldExpression, value, partitionKey); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( filter, fieldExpression, value, cancellationToken: token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( filter, fieldExpression, value, partitionKey, token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( filterExpression, fieldExpression, value, cancellationToken: token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ReplacesOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( filterExpression, fieldExpression, value, partitionKey); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( filterExpression, fieldExpression, value, partitionKey, token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOne( It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithClientSessionAndDocument_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var collection = SetupCollection(); // Act var result = Sut.UpdateOne(session.Object, document); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); ReplaceOptions expectedOptions = null; collection .Verify( x => x.ReplaceOne( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), document, expectedOptions, CancellationToken.None), Times.Once()); } [Fact] public void WithClientSessionAndDocumentAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var token = new CancellationToken(true); var collection = SetupCollection(); // Act var result = Sut.UpdateOne(session.Object, document, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); ReplaceOptions expectedOptions = null; collection .Verify( x => x.ReplaceOne( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), document, expectedOptions, token), Times.Once()); } [Fact] public void WithClientSessionAndDocumentAndUpdateDefinition_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var collection = SetupCollection(); var updateDefinition = Builders.Update.Set(x => x.Id, document.Id); // Act var result = Sut.UpdateOne(session.Object, document, updateDefinition); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), updateDefinition, null, CancellationToken.None), Times.Once()); } [Fact] public void WithClientSessionAndDocumentAndUpdateDefinitionAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var collection = SetupCollection(); var updateDefinition = Builders.Update.Set(x => x.Id, document.Id); var token = new CancellationToken(true); // Act var result = Sut.UpdateOne(session.Object, document, updateDefinition, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), updateDefinition, null, token), Times.Once()); } [Fact] public void WithClientSessionAndDocumentAndFieldExpressionAndValue_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne(session.Object, document, fieldExpression, value); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithClientSessionAndDocumentAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var document = Fixture.Create(); var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne(session.Object, document, fieldExpression, value, token); // Assert result.Should().BeTrue(); var expectedFilter = Builders.Filter.Eq("Id", document.Id); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithClientSessionAndFilterAndFieldExpressionAndValueAndPartitionKey_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( session.Object, filter, fieldExpression, value, partitionKey); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithClientSessionAndFilterAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( session.Object, filter, fieldExpression, value, cancellationToken: token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithClientSessionAndFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var token = new CancellationToken(true); var filter = Builders.Filter.Eq(x => x.SomeContent, "SomeContent"); Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( session.Object, filter, fieldExpression, value, partitionKey, token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(filter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var collection = SetupCollection(); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( session.Object, filterExpression, fieldExpression, value, cancellationToken: token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } [Fact] public void WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( session.Object, filterExpression, fieldExpression, value, partitionKey); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, CancellationToken.None), Times.Once()); } [Fact] public void WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne() { // Arrange var session = MockOf(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var collection = SetupCollection(partitionKey); var token = new CancellationToken(true); Expression> filterExpression = testDocument => testDocument.SomeContent == "SomeContent"; Expression> fieldExpression = testDocument => testDocument.SomeContent; // Act var result = Sut.UpdateOne( session.Object, filterExpression, fieldExpression, value, partitionKey, token); // Assert result.Should().BeTrue(); var expectedUpdateDefinition = Builders.Update.Set(x => x.SomeContent, value); var expectedFilter = Builders.Filter.Where(filterExpression); collection .Verify( x => x.UpdateOne( session.Object, It.Is>(f => f.EquivalentTo(expectedFilter)), It.Is>(u => u.EquivalentTo(expectedUpdateDefinition)), null, token), Times.Once()); } private Mock> SetupCollection(string partitionKey = null) { var replacedId = Fixture.Create(); var count = Fixture.Create(); var replaceResult = new ReplaceOneResult.Acknowledged(count, 1, new BsonBinaryData(replacedId, GuidRepresentation.Standard)); var updateResult = new UpdateResult.Acknowledged(count, 1, new BsonBinaryData(replacedId, GuidRepresentation.Standard)); var collection = MockOf>(); collection .Setup( x => x.ReplaceOne( It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(replaceResult); collection .Setup( x => x.UpdateOne( It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(updateResult); collection .Setup( x => x.ReplaceOne( It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(replaceResult); collection .Setup( x => x.UpdateOne( It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(updateResult); var dbContext = MockOf(); dbContext .Setup(x => x.GetCollection(partitionKey)) .Returns(collection.Object); return collection; } } ================================================ FILE: CoreUnitTests/Infrastructure/FilterDefinitionExtensions.cs ================================================ namespace CoreUnitTests.Infrastructure; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver; public static class FilterDefinitionExtensions { public static string RenderToJson(this FilterDefinition filter) => filter.Render(new RenderArgs(BsonSerializer.SerializerRegistry.GetSerializer(), BsonSerializer.SerializerRegistry)).ToJson(); public static bool EquivalentTo(this FilterDefinition filter, FilterDefinition other) => filter.RenderToJson() == other.RenderToJson(); } ================================================ FILE: CoreUnitTests/Infrastructure/GenericTestContext.cs ================================================ using AutoFixture; using AutoFixture.AutoMoq; using Moq; namespace CoreUnitTests.Infrastructure; public class GenericTestContext { public GenericTestContext() => Fixture = new Fixture().Customize(new AutoMoqCustomization()); protected Mock MockOf() where T : class => Fixture.Freeze>(); protected IFixture Fixture { get; set; } protected TSut Sut => Fixture.Create(); } ================================================ FILE: CoreUnitTests/Infrastructure/IndexExtensions.cs ================================================ using System; using MongoDB.Bson.Serialization; using MongoDB.Driver; using MongoDbGenericRepository.Models; using Xunit.Abstractions; namespace CoreUnitTests.Infrastructure; public static class IndexExtensions { public static bool EqualToJson(this IndexKeysDefinition keys, string json, ITestOutputHelper output) { var indexModelRendered = RenderIndexModelKeys(keys); var result = indexModelRendered.Equals(json, StringComparison.Ordinal); if (!result && output != null) { output.WriteLine($"Expected: {json}"); output.WriteLine($"Actual: {indexModelRendered}"); } return result; } public static bool EqualToJson(this IndexKeysDefinition keys, string json) { var indexModelRendered = RenderIndexModelKeys(keys); return indexModelRendered.Equals(json, StringComparison.Ordinal); } public static bool EqualTo(this IndexCreationOptions x, CreateIndexOptions y) => x.Unique == y.Unique && x.TextIndexVersion == y.TextIndexVersion && x.SphereIndexVersion == y.SphereIndexVersion && x.Sparse == y.Sparse && x.Name == y.Name && x.Min == y.Min && x.Max == y.Max && x.LanguageOverride == y.LanguageOverride && x.ExpireAfter == y.ExpireAfter && x.DefaultLanguage == y.DefaultLanguage && x.Bits == y.Bits && x.Background == y.Background && x.Version == y.Version; public static bool EqualTo(this CreateIndexOptions x, IndexCreationOptions y) => x.Unique == y.Unique && x.TextIndexVersion == y.TextIndexVersion && x.SphereIndexVersion == y.SphereIndexVersion && x.Sparse == y.Sparse && x.Name == y.Name && x.Min == y.Min && x.Max == y.Max && x.LanguageOverride == y.LanguageOverride && x.ExpireAfter == y.ExpireAfter && x.DefaultLanguage == y.DefaultLanguage && x.Bits == y.Bits && x.Background == y.Background && x.Version == y.Version; private static string RenderIndexModelKeys(IndexKeysDefinition keys) { var indexModelRendered = keys.Render(new RenderArgs( BsonSerializer.SerializerRegistry.GetSerializer(), BsonSerializer.SerializerRegistry)); var result = indexModelRendered.ToString(); return result.Replace(" ", ""); } } ================================================ FILE: CoreUnitTests/Infrastructure/Model/Child.cs ================================================ namespace CoreUnitTests.Infrastructure.Model; public class Child { public Child(string type, string value) { Type = type; Value = value; } public string Type { get; set; } public string Value { get; set; } } ================================================ FILE: CoreUnitTests/Infrastructure/Model/Nested.cs ================================================ using System; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace CoreUnitTests.Infrastructure.Model; public class Nested { public DateTime SomeDate { get; set; } [BsonRepresentation(BsonType.Decimal128)] public decimal SomeAmount { get; set; } } ================================================ FILE: CoreUnitTests/Infrastructure/Model/PartitionedTestDocument.cs ================================================ using MongoDbGenericRepository.Models; namespace CoreUnitTests.Infrastructure.Model; public class PartitionedTestDocument : TestDocument, IPartitionedDocument { /// public string PartitionKey { get; set; } = "PartitionedTestDocument"; } ================================================ FILE: CoreUnitTests/Infrastructure/Model/TestDocument.cs ================================================ using System; using System.Collections.Generic; using MongoDbGenericRepository.Models; namespace CoreUnitTests.Infrastructure.Model; public class TestDocument : Document { public TestDocument() { Version = 2; Nested = new Nested {SomeDate = DateTime.UtcNow}; Children = new List(); } public int SomeValue { get; set; } public decimal SomeDecimalValue { get; set; } public string SomeContent { get; set; } public string SomeContent2 { get; set; } public string SomeContent3 { get; set; } public int GroupingKey { get; set; } public Guid OtherGroupingKey { get; set; } public Nested Nested { get; set; } public List Children { get; set; } } ================================================ FILE: CoreUnitTests/Infrastructure/Model/TestDocumentWithKey.cs ================================================ using System; using System.Collections.Generic; using MongoDbGenericRepository.Models; namespace CoreUnitTests.Infrastructure.Model; public class TestDocumentWithKey : IDocument where TKey : IEquatable { public TKey Id { get; set; } public int Version { get; set; } public TestDocumentWithKey() { Version = 2; Nested = new Nested { SomeDate = DateTime.UtcNow }; Children = new List(); } public int SomeValue { get; set; } public int SomeDecimalValue { get; set; } public string SomeContent { get; set; } public string SomeContent2 { get; set; } public string SomeContent3 { get; set; } public int GroupingKey { get; set; } public Nested Nested { get; set; } public List Children { get; set; } } ================================================ FILE: CoreUnitTests/Infrastructure/Model/TestProjection.cs ================================================ using System; namespace CoreUnitTests.Infrastructure.Model; public class TestProjection { public Guid TestDocumentId { get; set; } public DateTime NestedData { get; set; } public int Count { get; set; } } ================================================ FILE: CoreUnitTests/Infrastructure/TestKeyedMongoRepository.cs ================================================ using System; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Create; using MongoDbGenericRepository.DataAccess.Delete; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.DataAccess.Read; using MongoDbGenericRepository.DataAccess.Update; namespace CoreUnitTests.Infrastructure; public class TestKeyedMongoRepository : BaseMongoRepository where TKey : IEquatable { public TestKeyedMongoRepository(IMongoDatabase mongoDatabase) : base(mongoDatabase) { } public void SetIndexHandler(IMongoDbIndexHandler indexHandler) => MongoDbIndexHandler = indexHandler; public void SetDbCreator(IMongoDbCreator creator) => MongoDbCreator = creator; public void SetReader(IMongoDbReader reader) => MongoDbReader = reader; public void SetEraser(IMongoDbEraser eraser) => MongoDbEraser = eraser; public void SetUpdater(IMongoDbUpdater updater) => MongoDbUpdater = updater; } ================================================ FILE: CoreUnitTests/Infrastructure/TestKeyedMongoRepositoryContext.cs ================================================ using System; using AutoFixture; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Create; using MongoDbGenericRepository.DataAccess.Delete; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.DataAccess.Read; using MongoDbGenericRepository.DataAccess.Update; using Moq; namespace CoreUnitTests.Infrastructure; public class TestKeyedMongoRepositoryContext where TKey : IEquatable { private readonly Mock mongoDatabase; private TestKeyedMongoRepository sut; protected TestKeyedMongoRepositoryContext() { mongoDatabase = new Mock(); Fixture = new Fixture(); } protected Fixture Fixture { get; set; } protected TestKeyedMongoRepository Sut { get { if (sut != null) { return sut; } sut = new TestKeyedMongoRepository(mongoDatabase.Object); if (IndexHandler != null) { sut.SetIndexHandler(IndexHandler.Object); } if (Creator != null) { sut.SetDbCreator(Creator.Object); } if (Reader != null) { sut.SetReader(Reader.Object); } if (Eraser != null) { sut.SetEraser(Eraser.Object); } if (Updater != null) { sut.SetUpdater(Updater.Object); } return sut; } } protected Mock IndexHandler { get; set; } protected Mock Creator { get; set; } protected Mock Reader { get; set; } protected Mock Eraser { get; set; } protected Mock Updater { get; set; } } ================================================ FILE: CoreUnitTests/Infrastructure/TestKeyedReadOnlyMongoRepository.cs ================================================ using System; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Read; namespace CoreUnitTests.Infrastructure; public class TestKeyedReadOnlyMongoRepository : ReadOnlyMongoRepository where TKey : IEquatable { /// public TestKeyedReadOnlyMongoRepository(string connectionString, string databaseName = null) : base(connectionString, databaseName) { } /// public TestKeyedReadOnlyMongoRepository(IMongoDatabase mongoDatabase) : base(mongoDatabase) { } /// public TestKeyedReadOnlyMongoRepository(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } public void SetReader(IMongoDbReader reader) => MongoDbReader = reader; } ================================================ FILE: CoreUnitTests/Infrastructure/TestKeyedReadOnlyMongoRepositoryContext.cs ================================================ using System; using AutoFixture; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; namespace CoreUnitTests.Infrastructure; public class TestKeyedReadOnlyMongoRepositoryContext where TKey : IEquatable { private readonly Mock mongoDatabase; private TestKeyedReadOnlyMongoRepository sut; protected TestKeyedReadOnlyMongoRepositoryContext() { mongoDatabase = new Mock(); Fixture = new Fixture(); } protected Fixture Fixture { get; set; } protected TestKeyedReadOnlyMongoRepository Sut { get { if (sut != null) { return sut; } sut = new TestKeyedReadOnlyMongoRepository(mongoDatabase.Object); if (Reader != null) { sut.SetReader(Reader.Object); } return sut; } } protected Mock Reader { get; set; } } ================================================ FILE: CoreUnitTests/Infrastructure/TestMongoRepository.cs ================================================ using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Create; using MongoDbGenericRepository.DataAccess.Delete; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.DataAccess.Read; using MongoDbGenericRepository.DataAccess.Update; namespace CoreUnitTests.Infrastructure; public class TestMongoRepository : BaseMongoRepository { public TestMongoRepository(IMongoDatabase mongoDatabase) : base(mongoDatabase) { } public void SetIndexHandler(IMongoDbIndexHandler indexHandler) => MongoDbIndexHandler = indexHandler; public void SetDbCreator(IMongoDbCreator creator) => MongoDbCreator = creator; public void SetReader(IMongoDbReader reader) => MongoDbReader = reader; public void SetEraser(IMongoDbEraser eraser) => MongoDbEraser = eraser; public void SetUpdater(IMongoDbUpdater updater) => MongoDbUpdater = updater; } ================================================ FILE: CoreUnitTests/Infrastructure/TestMongoRepositoryContext.cs ================================================ using AutoFixture; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Create; using MongoDbGenericRepository.DataAccess.Delete; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.DataAccess.Read; using MongoDbGenericRepository.DataAccess.Update; using Moq; namespace CoreUnitTests.Infrastructure; public class TestMongoRepositoryContext { private readonly Mock _mongoDatabase; private TestMongoRepository _sut; protected TestMongoRepositoryContext() { _mongoDatabase = new Mock(); Fixture = new Fixture(); } public Fixture Fixture { get; set; } protected TestMongoRepository Sut { get { if (_sut == null) { _sut = new TestMongoRepository(_mongoDatabase.Object); if (IndexHandler != null) { _sut.SetIndexHandler(IndexHandler.Object); } if (Creator != null) { _sut.SetDbCreator(Creator.Object); } if (Reader != null) { _sut.SetReader(Reader.Object); } if (Eraser != null) { _sut.SetEraser(Eraser.Object); } if (Updater != null) { _sut.SetUpdater(Updater.Object); } } return _sut; } } protected Mock IndexHandler { get; set; } protected Mock Creator { get; set; } protected Mock Reader { get; set; } protected Mock Eraser { get; set; } protected Mock Updater { get; set; } } ================================================ FILE: CoreUnitTests/Infrastructure/TestReadOnlyMongoRepository.cs ================================================ using System; using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.DataAccess.Read; namespace CoreUnitTests.Infrastructure; public class TestReadOnlyMongoRepository : ReadOnlyMongoRepository { /// public TestReadOnlyMongoRepository(string connectionString, string databaseName = null) : base(connectionString, databaseName) { } /// public TestReadOnlyMongoRepository(IMongoDatabase mongoDatabase) : base(mongoDatabase) { } /// public TestReadOnlyMongoRepository(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } public void SetReader(IMongoDbReader reader) => MongoDbReader = reader; } ================================================ FILE: CoreUnitTests/Infrastructure/TestReadOnlyMongoRepositoryContext.cs ================================================ using System; using AutoFixture; using AutoFixture.AutoMoq; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; namespace CoreUnitTests.Infrastructure; public class TestReadOnlyMongoRepositoryContext { private readonly Mock mongoDatabase; private TestReadOnlyMongoRepository sut; protected TestReadOnlyMongoRepositoryContext() { mongoDatabase = new Mock(); Fixture = new Fixture().Customize(new AutoMoqCustomization()); } protected IFixture Fixture { get; set; } protected TestReadOnlyMongoRepository Sut { get { if (sut != null) { return sut; } sut = Fixture.Create(); if (Reader != null) { sut.SetReader(Reader.Object); } return sut; } } protected Mock Reader { get; set; } protected Mock MockOf() where T : class => Fixture.Freeze>(); } ================================================ FILE: CoreUnitTests/Infrastructure/UpdateDefinitionExtensions.cs ================================================ using System; using MongoDB.Bson.Serialization; using MongoDB.Driver; namespace CoreUnitTests.Infrastructure; public static class UpdateDefinitionExtensions { public static bool EquivalentTo(this UpdateDefinition update, UpdateDefinition expected) { var renderedUpdate = update.Render(new RenderArgs( BsonSerializer.SerializerRegistry.GetSerializer(), BsonSerializer.SerializerRegistry)); var renderedExpected = expected.Render(new RenderArgs( BsonSerializer.SerializerRegistry.GetSerializer(), BsonSerializer.SerializerRegistry)); return renderedUpdate.Equals(renderedExpected); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/AddTests/AddManyAsyncTests.cs ================================================ using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.AddTests; public class AddManyAsyncTests : TestKeyedMongoRepositoryContext { [Fact] public async Task WithDocument_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany>().ToList(); Creator = new Mock(); // Act await Sut.AddManyAsync(documents); // Assert Creator.Verify(x => x.AddManyAsync, int>(documents, CancellationToken.None), Times.Once); } [Fact] public async Task WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); Creator = new Mock(); // Act await Sut.AddManyAsync(documents, token); // Assert Creator.Verify(x => x.AddManyAsync, int>(documents, token), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/AddTests/AddManyTests.cs ================================================ using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.AddTests; public class AddManyTests : TestKeyedMongoRepositoryContext { [Fact] public void WithDocument_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany>().ToList(); Creator = new Mock(); // Act Sut.AddMany(documents); // Assert Creator.Verify(x => x.AddMany, int>(documents, CancellationToken.None), Times.Once); } [Fact] public void WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var documents = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); Creator = new Mock(); // Act Sut.AddMany(documents, token); // Assert Creator.Verify(x => x.AddMany, int>(documents, token), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/AddTests/AddOneAsyncTests.cs ================================================ using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.AddTests; public class AddOneAsyncTests : TestKeyedMongoRepositoryContext { [Fact] public async Task WithDocument_ShouldAddOne() { // Arrange var document = Fixture.Create>(); Creator = new Mock(); // Act await Sut.AddOneAsync(document); // Assert Creator.Verify(x => x.AddOneAsync, int>(document, CancellationToken.None), Times.Once); } [Fact] public async Task WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Creator = new Mock(); // Act await Sut.AddOneAsync(document, token); // Assert Creator.Verify(x => x.AddOneAsync, int>(document, token), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/AddTests/AddOneTests.cs ================================================ using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Create; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.AddTests; public class AddOneTests : TestKeyedMongoRepositoryContext { [Fact] public void WithDocument_ShouldAddOne() { // Arrange var document = Fixture.Create>(); Creator = new Mock(); // Act Sut.AddOne(document); // Assert Creator.Verify(x => x.AddOne, int>(document, CancellationToken.None), Times.Once); } [Fact] public void WithDocumentAndCancellationToken_ShouldAddOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Creator = new Mock(); // Act Sut.AddOne(document, token); // Assert Creator.Verify(x => x.AddOne, int>(document, token), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/DeleteTests/DeleteManyAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.DeleteTests; public class DeleteManyAsyncTests : TestKeyedMongoRepositoryContext { [Fact] public async Task WithDocuments_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany>().ToList(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>(It.IsAny>>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(documents); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(documents, CancellationToken.None), Times.Once); } [Fact] public async Task WithDocumentsAndCancellationToken_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany>().ToList(); var count = Fixture.Create(); var cancellationToken = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>(It.IsAny>>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(documents, cancellationToken); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(documents, cancellationToken), Times.Once); } [Fact] public async Task WithFilter_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(filter, null, token), Times.Once); } [Fact] public async Task WithFilterAndPartitionKey_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteManyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteManyAsync(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteManyAsync, int>(filter, partitionKey, token), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/DeleteTests/DeleteManyTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.DeleteTests; public class DeleteManyTests : TestKeyedMongoRepositoryContext { [Fact] public void WithDocuments_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany>().ToList(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>(It.IsAny>>(), CancellationToken.None)) .Returns(count); // Act var result = Sut.DeleteMany(documents); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(documents, CancellationToken.None), Times.Once); } [Fact] public void WithDocumentsAndCancellationToken_ShouldDeleteMany() { // Arrange var documents = Fixture.CreateMany>().ToList(); var count = Fixture.Create(); var token = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>(It.IsAny>>(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany(documents, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(documents, token), Times.Once); } [Fact] public void WithFilter_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>(It.IsAny, bool>>>(), null, CancellationToken.None)) .Returns(count); // Act var result = Sut.DeleteMany(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup( x => x.DeleteMany, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(filter, null, token), Times.Once); } [Fact] public void WithFilterAndPartitionKey_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup( x => x.DeleteMany, int>( It.IsAny, bool>>>(), It.IsAny(), CancellationToken.None)) .Returns(count); // Act var result = Sut.DeleteMany(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany() { // Arrange var content = Fixture.Create(); var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteMany, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteMany(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteMany, int>(filter, partitionKey, token), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/DeleteTests/DeleteOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.DeleteTests; public class DeleteOneAsyncTests : TestKeyedMongoRepositoryContext { [Fact] public async Task WithDocument_ShouldDeleteOne() { // Arrange var document = Fixture.Create>(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(document); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(document, CancellationToken.None), Times.Once); } [Fact] public async Task WithDocumentAndCancellationToken_ShouldDeleteOne() { // Arrange var document = Fixture.Create>(); var count = Fixture.Create(); var token = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny>(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(document, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(document, token), Times.Once); } [Fact] public async Task WithFilter_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(filter, null, token), Times.Once); } [Fact] public async Task WithFilterAndPartitionKey_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOneAsync, int>(It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.DeleteOneAsync(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOneAsync, int>(filter, partitionKey, token), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/DeleteTests/DeleteOneTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Delete; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.DeleteTests; public class DeleteOneTests : TestKeyedMongoRepositoryContext { [Fact] public void WithDocument_ShouldDeleteOne() { // Arrange var document = Fixture.Create>(); var count = Fixture.Create(); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne, int>( It.IsAny>(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(document); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(document, CancellationToken.None), Times.Once); } [Fact] public void WithDocumentAndCancellationToken_ShouldDeleteOne() { // Arrange var document = Fixture.Create>(); var count = Fixture.Create(); var token = new CancellationToken(true); Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne, int>( It.IsAny>(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(document, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(document, token), Times.Once); } [Fact] public void WithFilter_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(filter); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(filter, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(filter, null, token), Times.Once); } [Fact] public void WithFilterAndPartitionKey_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(filter, partitionKey); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne() { // Arrange var count = Fixture.Create(); var content = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Expression, bool>> filter = x => x.SomeContent == content; Eraser = new Mock(); Eraser .Setup(x => x.DeleteOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.DeleteOne(filter, partitionKey, token); // Assert result.Should().Be(count); Eraser.Verify(x => x.DeleteOne, int>(filter, partitionKey, token), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/IndexTests/CreateAscendingIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.IndexTests; public class CreateAscendingIndexAsyncTests : TestKeyedMongoRepositoryContext { private readonly Expression, object>> keyedFieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(keyedFieldExpression); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>(keyedFieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(keyedFieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>(keyedFieldExpression, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(keyedFieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(keyedFieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(keyedFieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(keyedFieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(keyedFieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateAscendingIndexAsync(keyedFieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateAscendingIndexAsync, int>( keyedFieldExpression, options, partitionKey, token)); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/IndexTests/CreateCombinedTextIndexAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.IndexTests; public class CreateCombinedTextIndexAsyncTests : TestKeyedMongoRepositoryContext { private readonly List, object>>> keyedFieldExpressions = new() {t => t.SomeContent2, t => t.SomeContent3}; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(keyedFieldExpressions); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(keyedFieldExpressions, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>(keyedFieldExpressions, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(keyedFieldExpressions, options); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(keyedFieldExpressions, options, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(keyedFieldExpressions, partitionKey); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(keyedFieldExpressions, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(keyedFieldExpressions, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateCombinedTextIndexAsync(keyedFieldExpressions, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateCombinedTextIndexAsync, int>( keyedFieldExpressions, options, partitionKey, token)); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/IndexTests/CreateDescendingIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.IndexTests; public class CreateDescendingIndexAsyncTests : TestKeyedMongoRepositoryContext { private readonly Expression, object>> keyedFieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(keyedFieldExpression); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>(keyedFieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(keyedFieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>(keyedFieldExpression, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(keyedFieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(keyedFieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(keyedFieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(keyedFieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(keyedFieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateDescendingIndexAsync(keyedFieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateDescendingIndexAsync, int>( keyedFieldExpression, options, partitionKey, token)); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/IndexTests/CreateHashedIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.IndexTests; public class CreateHashedIndexAsyncTests : TestKeyedMongoRepositoryContext { private readonly Expression, object>> keyedFieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(keyedFieldExpression); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>(keyedFieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(keyedFieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>(keyedFieldExpression, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(keyedFieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(keyedFieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(keyedFieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(keyedFieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(keyedFieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateHashedIndexAsync(keyedFieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateHashedIndexAsync, int>( keyedFieldExpression, options, partitionKey, token)); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/IndexTests/CreateTextIndexAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.IndexTests; public class CreateTextIndexAsyncTests : TestKeyedMongoRepositoryContext { private readonly Expression, object>> keyedFieldExpression = t => t.SomeContent2; [Fact] public async Task WithFieldExpression_CreatesIndex() { // Arrange IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(keyedFieldExpression); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>(keyedFieldExpression, null, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndCancellationToken_CreatesIndex() { // Arrange var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(keyedFieldExpression, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>(keyedFieldExpression, null, null, token)); } [Fact] public async Task WithFieldExpressionAndOptions_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(keyedFieldExpression, options); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, options, null, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex() { // Arrange var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(keyedFieldExpression, options, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, options, null, token)); } [Fact] public async Task WithFieldExpressionAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(keyedFieldExpression, partitionKey); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, null, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(keyedFieldExpression, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, null, partitionKey, token)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(keyedFieldExpression, options, partitionKey); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, options, partitionKey, CancellationToken.None)); } [Fact] public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var indexName = Fixture.Create(); var options = new IndexCreationOptions { Name = indexName }; IndexHandler = new Mock(); // Act await Sut.CreateTextIndexAsync(keyedFieldExpression, options, partitionKey, token); // Assert IndexHandler.Verify( x => x.CreateTextIndexAsync, int>( keyedFieldExpression, options, partitionKey, token)); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/IndexTests/DropIndexAsyncTests.cs ================================================ using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.IndexTests; public class DropIndexAsyncTests : TestKeyedMongoRepositoryContext { [Fact] public async Task WitIndexName_DropsIndex() { // Arrange var indexName = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync>(indexName); // Assert IndexHandler.Verify( x => x.DropIndexAsync, int>(indexName, null, CancellationToken.None)); } [Fact] public async Task WitIndexNameAndCancellationToken_DropsIndex() { // Arrange var indexName = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync>(indexName, token); // Assert IndexHandler.Verify( x => x.DropIndexAsync, int>(indexName, null, token)); } [Fact] public async Task WitIndexNameAndPartitionKey_DropsIndex() { // Arrange var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync>(indexName, partitionKey); // Assert IndexHandler.Verify( x => x.DropIndexAsync, int>(indexName, partitionKey, CancellationToken.None)); } [Fact] public async Task WitIndexNameAndPartitionKeyAndCancellationToken_DropsIndex() { // Arrange var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler = new Mock(); // Act await Sut.DropIndexAsync>(indexName, partitionKey, token); // Assert IndexHandler.Verify( x => x.DropIndexAsync, int>(indexName, partitionKey, token)); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/IndexTests/GetIndexNamesAsyncTests.cs ================================================ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using MongoDbGenericRepository.DataAccess.Index; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.IndexTests; public class GetIndexNamesAsyncTests : TestKeyedMongoRepositoryContext { [Fact] public async Task WithNoParameters_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); IndexHandler .Setup(x => x.GetIndexesNamesAsync, int>(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync>(); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync, int>(null, CancellationToken.None), Times.Once()); } [Fact] public async Task WithCancellationToken_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); var token = new CancellationToken(true); IndexHandler .Setup(x => x.GetIndexesNamesAsync, int>(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync>(token); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync, int>(null, token), Times.Once()); } [Fact] public async Task WithPartitionKey_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); IndexHandler .Setup(x => x.GetIndexesNamesAsync, int>(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync>(partitionKey); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync, int>(partitionKey, CancellationToken.None), Times.Once()); } [Fact] public async Task WithPartitionKeyAndCancellationToken_ReturnsIndexNames() { // Arrange IndexHandler = new Mock(); var indexName = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); IndexHandler .Setup(x => x.GetIndexesNamesAsync, int>(It.IsAny(), It.IsAny())) .ReturnsAsync(new List { indexName }); // Act var result = await Sut.GetIndexesNamesAsync>(partitionKey, token); // Assert Assert.NotNull(result); Assert.Contains(result, x => x == indexName); IndexHandler.Verify(x => x.GetIndexesNamesAsync, int>(partitionKey, token), Times.Once()); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/UpdateTests/UpdateManyAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.UpdateTests; public class UpdateManyAsyncTests : TestKeyedMongoRepositoryContext { private readonly UpdateDefinition> updateDefinition = Builders>.Update.Set(x => x.SomeContent, "Updated"); private readonly Expression, string>> fieldExpression = x => x.SomeContent; private readonly FilterDefinition> filterDefinition = Builders>.Filter.Eq(x => x.Id, 1); private readonly Expression, bool>> filterExpression = x => x.SomeContent == "SomeContent"; [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( filterDefinition, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( filterDefinition, fieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( filterDefinition, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( filterDefinition, fieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( filterExpression, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( filterExpression, fieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( filterExpression, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int, string>( filterExpression, fieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, updateDefinition); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( filterExpression, updateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( filterExpression, updateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, updateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( filterExpression, updateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterExpression, updateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( filterExpression, updateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, updateDefinition); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( filterDefinition, updateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndUpdateDefinitionCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( filterDefinition, updateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, updateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( filterDefinition, updateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public async Task WithFilterDefinitionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateManyAsync, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); // Act var result = await Sut.UpdateManyAsync(filterDefinition, updateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateManyAsync, int>( filterDefinition, updateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/UpdateTests/UpdateManyTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.UpdateTests; public class UpdateManyTests : TestKeyedMongoRepositoryContext { private readonly Expression, string>> fieldExpression = x => x.SomeContent; private readonly FilterDefinition> filterDefinition = Builders>.Filter.Eq(x => x.Id, 1); private readonly Expression, bool>> filterExpression = x => x.SomeContent == "SomeContent"; private readonly UpdateDefinition> updateDefinition = Builders>.Update.Set(x => x.SomeContent, "Updated"); [Fact] public void WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateMany, int, string>( filterDefinition, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateMany, int, string>( filterDefinition, fieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateMany, int, string>( filterDefinition, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany, int, string>( filterDefinition, fieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateMany, int, string>( filterExpression, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateMany, int, string>( filterExpression, fieldExpression, value, null, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateMany, int, string>( filterExpression, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany, int, string>( filterExpression, fieldExpression, value, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, updateDefinition); // Assert Updater.Verify( x => x.UpdateMany, int>( filterExpression, updateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateMany, int>( filterExpression, updateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, updateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateMany, int>( filterExpression, updateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterExpression, updateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany, int>( filterExpression, updateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndUpdateDefinition_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, updateDefinition); // Assert Updater.Verify( x => x.UpdateMany, int>( filterDefinition, updateDefinition, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndUpdateDefinitionCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateMany, int>( filterDefinition, updateDefinition, null, token), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndUpdateDefinitionAndPartitionKey_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, updateDefinition, partitionKey); // Assert Updater.Verify( x => x.UpdateMany, int>( filterDefinition, updateDefinition, partitionKey, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void WithFilterDefinitionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateMany, int>( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); // Act var result = Sut.UpdateMany(filterDefinition, updateDefinition, partitionKey, token); // Assert Updater.Verify( x => x.UpdateMany, int>( filterDefinition, updateDefinition, partitionKey, token), Times.Once); result.Should().Be(count); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/UpdateTests/UpdateOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.UpdateTests; public class UpdateOneAsyncTests : TestKeyedMongoRepositoryContext { private readonly UpdateDefinition> updateDefinition = Builders>.Update.Set(x => x.SomeContent, "Updated"); private readonly Expression, string>> fieldExpression = x => x.SomeContent; private readonly FilterDefinition> filterDefinition = Builders>.Filter.Eq(x => x.Id, 1); private readonly Expression, bool>> filterExpression = x => x.SomeContent == "SomeContent"; [Fact] public async Task WithDocument_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup(x => x.UpdateOneAsync, int>(It.IsAny>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document); // Assert Updater.Verify(x => x.UpdateOneAsync, int>(document, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup(x => x.UpdateOneAsync, int>(It.IsAny>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, token); // Assert Updater.Verify(x => x.UpdateOneAsync, int>(document, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndUpdateDefinition_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int>( It.IsAny>(), It.IsAny>>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, updateDefinition); // Assert Updater.Verify( x => x.UpdateOneAsync, int>( document, updateDefinition, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int>( It.IsAny>(), It.IsAny>>(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int>( document, updateDefinition, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( document, fieldExpression, value, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithDocumentAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(document, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( document, fieldExpression, value, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterDefinition, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( filterDefinition, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterDefinition, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( filterDefinition, fieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterDefinition, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( filterDefinition, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterDefinition, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( filterDefinition, fieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterExpression, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( filterExpression, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterExpression, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( filterExpression, fieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterExpression, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( filterExpression, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOneAsync, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); // Act var result = await Sut.UpdateOneAsync(filterExpression, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOneAsync, int, string>( filterExpression, fieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } } ================================================ FILE: CoreUnitTests/KeyTypedRepositoryTests/UpdateTests/UpdateOneTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using Moq; using Xunit; namespace CoreUnitTests.KeyTypedRepositoryTests.UpdateTests; public class UpdateOneTests : TestKeyedMongoRepositoryContext { private readonly UpdateDefinition> updateDefinition = Builders>.Update.Set(x => x.SomeContent, "Updated"); private readonly Expression, string>> fieldExpression = x => x.SomeContent; private readonly FilterDefinition> filterDefinition = Builders>.Filter.Eq(x => x.Id, 1); private readonly Expression, bool>> filterExpression = x => x.SomeContent == "SomeContent"; [Fact] public void WithDocument_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup(x => x.UpdateOne, int>(It.IsAny>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document); // Assert Updater.Verify(x => x.UpdateOne, int>(document, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup(x => x.UpdateOne, int>(It.IsAny>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, token); // Assert Updater.Verify(x => x.UpdateOne, int>(document, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndUpdateDefinition_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int>( It.IsAny>(), It.IsAny>>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, updateDefinition); // Assert Updater.Verify( x => x.UpdateOne, int>( document, updateDefinition, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndUpdateDefinitionAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int>( It.IsAny>(), It.IsAny>>(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, updateDefinition, token); // Assert Updater.Verify( x => x.UpdateOne, int>( document, updateDefinition, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne, int, string>( document, fieldExpression, value, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithDocumentAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var document = Fixture.Create>(); var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(document, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( document, fieldExpression, value, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterDefinition, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne, int, string>( filterDefinition, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterDefinition, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( filterDefinition, fieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterDefinition, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOne, int, string>( filterDefinition, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterDefinitionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterDefinition, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( filterDefinition, fieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValue_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterExpression, fieldExpression, value); // Assert Updater.Verify( x => x.UpdateOne, int, string>( filterExpression, fieldExpression, value, null, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterExpression, fieldExpression, value, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( filterExpression, fieldExpression, value, null, token), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterExpression, fieldExpression, value, partitionKey); // Assert Updater.Verify( x => x.UpdateOne, int, string>( filterExpression, fieldExpression, value, partitionKey, CancellationToken.None), Times.Once); result.Should().BeTrue(); } [Fact] public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ShouldUpdateOne() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Updater = new Mock(); Updater .Setup( x => x.UpdateOne, int, string>( It.IsAny, bool>>>(), It.IsAny, string>>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); // Act var result = Sut.UpdateOne(filterExpression, fieldExpression, value, partitionKey, token); // Assert Updater.Verify( x => x.UpdateOne, int, string>( filterExpression, fieldExpression, value, partitionKey, token), Times.Once); result.Should().BeTrue(); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/AnyAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class AnyAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; [Fact] public async Task WithFilter_GetsResult() { // Arrange SetupReader(); // Act var result = await Sut.AnyAsync(filter); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndCancellationToken_GetsResult() { // Arrange var token = new CancellationToken(true); SetupReader(); // Act var result = await Sut.AnyAsync(filter, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(filter, null, token), Times.Once); } [Fact] public async Task WithFilterAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); SetupReader(); // Act var result = await Sut.AnyAsync(filter, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(); // Act var result = await Sut.AnyAsync(filter, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(filter, partitionKey, token), Times.Once); } private void SetupReader() { Reader = new Mock(); Reader .Setup( x => x.AnyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/AnyTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class AnyTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; [Fact] public void WithFilter_GetsResult() { // Arrange SetupReader(); // Act var result = Sut.Any(filter); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndCancellationToken_GetsResult() { // Arrange var token = new CancellationToken(true); SetupReader(); // Act var result = Sut.Any(filter, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(filter, null, token), Times.Once); } [Fact] public void WithFilterAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); SetupReader(); // Act var result = Sut.Any(filter, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(); // Act var result = Sut.Any(filter, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(filter, partitionKey, token), Times.Once); } private void SetupReader() { Reader = new Mock(); Reader .Setup( x => x.Any, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(true); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/CountAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class CountAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; [Fact] public async Task WithFilter_GetsOne() { // Arrange var count = Fixture.Create(); SetupReader(count); // Act var result = await Sut.CountAsync(filter); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndCancellationToken_GetsOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); SetupReader(count); // Act var result = await Sut.CountAsync(filter, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(filter, null, token), Times.Once); } [Fact] public async Task WithFilterAndPartitionKey_GetsOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(count); // Act var result = await Sut.CountAsync(filter, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(count); // Act var result = await Sut.CountAsync(filter, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(filter, partitionKey, token), Times.Once); } private void SetupReader(long count) { Reader = new Mock(); Reader .Setup( x => x.CountAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/CountTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class CountTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; [Fact] public void WithFilter_GetsOne() { // Arrange var count = Fixture.Create(); SetupReader(count); // Act var result = Sut.Count(filter); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndCancellationToken_GetsOne() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); SetupReader(count); // Act var result = Sut.Count(filter, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(filter, null, token), Times.Once); } [Fact] public void WithFilterAndPartitionKey_GetsOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(count); // Act var result = Sut.Count(filter, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(count); // Act var result = Sut.Count(filter, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(filter, partitionKey, token), Times.Once); } private void SetupReader(long count) { Reader = new Mock(); Reader .Setup( x => x.Count, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetAllAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetAllAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; [Fact] public async Task WithFilter_GetsOne() { // Arrange var document = Fixture.CreateMany>().ToList(); SetupReader(document); // Act var result = await Sut.GetAllAsync(filter); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndCancellationToken_GetsOne() { // Arrange var document = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetAllAsync(filter, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(filter, null, token), Times.Once); } [Fact] public async Task WithFilterAndPartitionKey_GetsOne() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetAllAsync(filter, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetAllAsync(filter, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(filter, partitionKey, token), Times.Once); } private void SetupReader(List> documents) { Reader = new Mock(); Reader .Setup( x => x.GetAllAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetAllTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetAllTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; [Fact] public void WithFilter_GetsOne() { // Arrange var document = Fixture.CreateMany>().ToList(); SetupReader(document); // Act var result = Sut.GetAll(filter); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndCancellationToken_GetsOne() { // Arrange var document = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetAll(filter, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(filter, null, token), Times.Once); } [Fact] public void WithFilterAndPartitionKey_GetsOne() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetAll(filter, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetAll(filter, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(filter, partitionKey, token), Times.Once); } private void SetupReader(List> documents) { Reader = new Mock(); Reader .Setup( x => x.GetAll, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(documents); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetByIdAsyncTests.cs ================================================ using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetByIdAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { [Fact] public async Task WithId_Gets() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = await Sut.GetByIdAsync>(document.Id); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync, int>(document.Id, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithIdAndCancellationToken_Gets() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByIdAsync>(document.Id, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync, int>(document.Id, null, token), Times.Once); } [Fact] public async Task WithIdAndPartitionKey_Gets() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByIdAsync>(document.Id, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync, int>(document.Id, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithIdAndPartitionKeyAndCancellationToken_Gets() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByIdAsync>(document.Id, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync, int>(document.Id, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByIdAsync, int>( It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetByIdTests.cs ================================================ using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetByIdTests : TestKeyedReadOnlyMongoRepositoryContext { [Fact] public void WithId_Gets() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = Sut.GetById>(document.Id); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById, int>(document.Id, null, CancellationToken.None), Times.Once); } [Fact] public void WithIdAndCancellationToken_Gets() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetById>(document.Id, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById, int>(document.Id, null, token), Times.Once); } [Fact] public void WithIdAndPartitionKey_Gets() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetById>(document.Id, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById, int>(document.Id, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithIdAndPartitionKeyAndCancellationToken_Gets() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetById>(document.Id, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById, int>(document.Id, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetById, int>( It.IsAny(), It.IsAny(), It.IsAny())) .Returns(document); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetByMaxAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetByMaxAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, object>> selector = document => document.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = await Sut.GetByMaxAsync(filter, selector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync, int>(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMaxAsync(filter, selector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync, int>(filter, selector, null, token), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByMaxAsync(filter, selector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync, int>(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMaxAsync(filter, selector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync, int>(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByMaxAsync, int>( It.IsAny, bool>>>(), It.IsAny, object>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetByMaxTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetByMaxTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, object>> selector = document => document.SomeValue; [Fact] public void WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = Sut.GetByMax(filter, selector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax, int>(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMax(filter, selector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax, int>(filter, selector, null, token), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetByMax(filter, selector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax, int>(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMax(filter, selector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax, int>(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByMax, int>( It.IsAny, bool>>>(), It.IsAny, object>>>(), It.IsAny(), It.IsAny())) .Returns(document); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetByMinAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetByMinAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, object>> selector = document => document.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = await Sut.GetByMinAsync(filter, selector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync, int>(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMinAsync(filter, selector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync, int>(filter, selector, null, token), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByMinAsync(filter, selector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync, int>(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMinAsync(filter, selector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync, int>(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByMinAsync, int>( It.IsAny, bool>>>(), It.IsAny, object>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetByMinTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetByMinTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, object>> selector = document => document.SomeValue; [Fact] public void WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = Sut.GetByMin(filter, selector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin, int>(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMin(filter, selector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin, int>(filter, selector, null, token), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetByMin(filter, selector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin, int>(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMin(filter, selector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin, int>(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByMin, int>( It.IsAny, bool>>>(), It.IsAny, object>>>(), It.IsAny(), It.IsAny())) .Returns(document); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetMaxValueAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetMaxValueAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> selector = document => document.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsMaxValue() { // Arrange var value = Fixture.Create(); SetupReader(value); // Act var result = await Sut.GetMaxValueAsync(filter, selector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync, int, int>(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = await Sut.GetMaxValueAsync(filter, selector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync, int, int>(filter, selector, null, token), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(value); // Act var result = await Sut.GetMaxValueAsync(filter, selector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync, int, int>(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = await Sut.GetMaxValueAsync(filter, selector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync, int, int>(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMaxValueAsync, int, int>( It.IsAny, bool>>>(), It.IsAny, int>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(value); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetMaxValueTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetMaxValueTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> selector = document => document.SomeValue; [Fact] public void WithFilterAndSelector_GetsMaxValue() { // Arrange var value = Fixture.Create(); SetupReader(value); // Act var result = Sut.GetMaxValue(filter, selector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue, int, int>(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = Sut.GetMaxValue(filter, selector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue, int, int>(filter, selector, null, token), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(value); // Act var result = Sut.GetMaxValue(filter, selector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue, int, int>(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = Sut.GetMaxValue(filter, selector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue, int, int>(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMaxValue, int, int>( It.IsAny, bool>>>(), It.IsAny, int>>>(), It.IsAny(), It.IsAny())) .Returns(value); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetMinValueAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetMinValueAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> selector = document => document.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsMaxValue() { // Arrange var value = Fixture.Create(); SetupReader(value); // Act var result = await Sut.GetMinValueAsync(filter, selector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync, int, int>(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = await Sut.GetMinValueAsync(filter, selector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync, int, int>(filter, selector, null, token), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(value); // Act var result = await Sut.GetMinValueAsync(filter, selector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync, int, int>(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = await Sut.GetMinValueAsync(filter, selector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync, int, int>(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMinValueAsync, int, int>( It.IsAny, bool>>>(), It.IsAny, int>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(value); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetMinValueTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetMinValueTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> selector = document => document.SomeValue; [Fact] public void WithFilterAndSelector_GetsMinValue() { // Arrange var value = Fixture.Create(); SetupReader(value); // Act var result = Sut.GetMinValue(filter, selector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue, int, int>(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsMinValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = Sut.GetMinValue(filter, selector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue, int, int>(filter, selector, null, token), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsMinValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(value); // Act var result = Sut.GetMinValue(filter, selector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue, int, int>(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMinValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = Sut.GetMinValue(filter, selector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue, int, int>(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMinValue, int, int>( It.IsAny, bool>>>(), It.IsAny, int>>>(), It.IsAny(), It.IsAny())) .Returns(value); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetOneAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; [Fact] public async Task WithFilter_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = await Sut.GetOneAsync(filter); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetOneAsync(filter, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(filter, null, token), Times.Once); } [Fact] public async Task WithFilterAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetOneAsync(filter, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetOneAsync(filter, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(filter, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetOneAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetOneTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetOneTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; [Fact] public void WithFilter_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = Sut.GetOne(filter); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(filter, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetOne(filter, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(filter, null, token), Times.Once); } [Fact] public void WithFilterAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetOne(filter, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(filter, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetOne(filter, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(filter, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(document); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GetSortedPaginatedAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GetSortedPaginatedAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.GroupingKey == 1; private readonly Expression, object>> selector = document => document.GroupingKey; private readonly SortDefinition> sortDefinition = Builders>.Sort.Ascending(document => document.GroupingKey); private const bool DefaultAscending = true; private const int DefaultSkipNumber = 0; private const int DefaultTakeNumber = 50; [Fact] public async Task WithFilterAndSortSelector_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector); // Assert VerifySelector(result, documents, DefaultAscending, DefaultSkipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndAscending_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var ascending = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, ascending); // Assert VerifySelector(result, documents, ascending, DefaultSkipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndSkipNumber_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var skipNumber = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, skipNumber: skipNumber); // Assert VerifySelector(result, documents, DefaultAscending, skipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndTakeNumber_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var ascending = Fixture.Create(); var takeNumber = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, ascending, takeNumber: takeNumber); // Assert VerifySelector(result, documents, ascending, DefaultSkipNumber, takeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndPartitionKey_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var partitionKey = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, partitionKey: partitionKey); // Assert VerifySelector(result, documents, DefaultAscending, DefaultSkipNumber, DefaultTakeNumber, partitionKey, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndCancellationToken_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var cancellationToken = new CancellationToken(true); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, cancellationToken: cancellationToken); // Assert VerifySelector(result, documents, DefaultAscending, DefaultSkipNumber, DefaultTakeNumber, null, cancellationToken); } [Fact] public async Task WithFilterAndSortDefinition_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition); // Assert VerifyDefinition(result, documents, DefaultSkipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortDefinitionAndSkipNumber_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); var skipNumber = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition, skipNumber); // Assert VerifyDefinition(result, documents, skipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortDefinitionAndTakeNumber_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); var takeNumber = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition, takeNumber: takeNumber); // Assert VerifyDefinition(result, documents, DefaultSkipNumber, takeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortDefinitionAndPartitionKey_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); var partitionKey = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition, partitionKey: partitionKey); // Assert VerifyDefinition(result, documents, DefaultSkipNumber, DefaultTakeNumber, partitionKey, CancellationToken.None); } [Fact] public async Task WithFilterAndSortDefinitionAndCancellationToken_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); var token = new CancellationToken(true); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition, cancellationToken: token); // Assert VerifyDefinition(result, documents, DefaultSkipNumber, DefaultTakeNumber, null, token); } private List> SetupReaderWithSortSelector() { var documents = Fixture.CreateMany>().ToList(); Reader = new Mock(); Reader.Setup( x => x.GetSortedPaginatedAsync, int>( It.IsAny, bool>>>(), It.IsAny, object>>>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents); return documents; } private void VerifySelector(List> result, List> documents, bool ascending, int skipNumber, int takeNumber, string partitionKey, CancellationToken cancellationToken) { result.Should().NotBeNull(); result.Should().BeEquivalentTo(documents); Reader.Verify( x => x.GetSortedPaginatedAsync, int>( filter, selector, ascending, skipNumber, takeNumber, partitionKey, cancellationToken), Times.Once); } private List> SetupReaderWithSortDefinition() { var documents = Fixture.CreateMany>().ToList(); Reader = new Mock(); Reader.Setup( x => x.GetSortedPaginatedAsync, int>( It.IsAny, bool>>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents); return documents; } private void VerifyDefinition(List> result, List> documents, int skipNumber, int takeNumber, string partitionKey, CancellationToken cancellationToken) { result.Should().NotBeNull(); result.Should().BeEquivalentTo(documents); Reader.Verify( x => x.GetSortedPaginatedAsync, int>( filter, sortDefinition, skipNumber, takeNumber, partitionKey, cancellationToken), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/GroupByTests.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class GroupByTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, int>> grouping = document => document.GroupingKey; private readonly Expression>, TestProjection>> projection = documents => new TestProjection {Count = documents.Count()}; private readonly Expression, bool>> filter = document => document.GroupingKey == 1; [Fact] public void WithGroupingCriteriaAndProjection_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(grouping, projection); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(grouping, projection, null, CancellationToken.None), Times.Once); } [Fact] public void WithGroupingCriteriaAndProjectionAndCancellationToken_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Reader = new Mock(); Reader .Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(grouping, projection, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(grouping, projection, null, token), Times.Once); } [Fact] public void WithGroupingCriteriaAndProjectionAndPartitionKey_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Reader = new Mock(); Reader .Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(grouping, projection, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(grouping, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithGroupingCriteriaAndProjectionAndPartitionKeyAndCancellationToken_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Reader = new Mock(); Reader .Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(grouping, projection, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(grouping, projection, partitionKey, token), Times.Once); } [Fact] public void WithFilterAndGroupingCriteriaAndProjection_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny,bool>>>(), It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(filter, grouping, projection); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(filter, grouping, projection, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndGroupingCriteriaAndProjectionAndCancellationToken_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny,bool>>>(), It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(filter, grouping, projection, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(filter, grouping, projection, null, token), Times.Once); } [Fact] public void WithFilterAndGroupingCriteriaAndProjectionAndPartitionKey_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny,bool>>>(), It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(filter, grouping, projection, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(filter, grouping, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndGroupingCriteriaAndProjectionAndPartitionKeyAndCancellationToken_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny,bool>>>(), It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(filter, grouping, projection, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(filter, grouping, projection, partitionKey, token), Times.Once); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/ProjectManyAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class ProjectManyAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, TestProjection>> projection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public async Task WithFilterAndProjection_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); SetupReader(projections); // Act var result = await Sut.ProjectManyAsync(filter, projection); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync, TestProjection, int>( filter, projection, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); SetupReader(projections); // Act var result = await Sut.ProjectManyAsync(filter, projection, token); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync, TestProjection, int>(filter, projection, null, token), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); SetupReader(projections); // Act var result = await Sut.ProjectManyAsync(filter, projection, partitionKey); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync, TestProjection, int>(filter, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(projections); // Act var result = await Sut.ProjectManyAsync(filter, projection, partitionKey, token); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync, TestProjection, int>(filter, projection, partitionKey, token), Times.Once); } private void SetupReader(List projections) { Reader = new Mock(); Reader .Setup( x => x.ProjectManyAsync, TestProjection, int>( It.IsAny, bool>>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(projections); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/ProjectManyTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class ProjectManyTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, TestProjection>> projection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public void WithFilterAndProjection_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); SetupReader(projections); // Act var result = Sut.ProjectMany(filter, projection); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectMany, TestProjection, int>( filter, projection, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); SetupReader(projections); // Act var result = Sut.ProjectMany(filter, projection, token); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectMany, TestProjection, int>(filter, projection, null, token), Times.Once); } [Fact] public void WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); SetupReader(projections); // Act var result = Sut.ProjectMany(filter, projection, partitionKey); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectMany, TestProjection, int>(filter, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(projections); // Act var result = Sut.ProjectMany(filter, projection, partitionKey, token); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectMany, TestProjection, int>(filter, projection, partitionKey, token), Times.Once); } private void SetupReader(List projections) { Reader = new Mock(); Reader .Setup( x => x.ProjectMany, TestProjection, int>( It.IsAny, bool>>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/ProjectOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class ProjectOneAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, TestProjection>> projection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public async Task WithFilterAndProjection_Projects() { // Arrange var expected = Fixture.Create(); SetupReader(expected); // Act var result = await Sut.ProjectOneAsync(filter, projection); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync, TestProjection, int>( filter, projection, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupReader(expected); // Act var result = await Sut.ProjectOneAsync(filter, projection, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync, TestProjection, int>(filter, projection, null, token), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(expected); // Act var result = await Sut.ProjectOneAsync(filter, projection, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync, TestProjection, int>(filter, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(expected); // Act var result = await Sut.ProjectOneAsync(filter, projection, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync, TestProjection, int>(filter, projection, partitionKey, token), Times.Once); } private void SetupReader(TestProjection result) { Reader = new Mock(); Reader .Setup( x => x.ProjectOneAsync, TestProjection, int>( It.IsAny, bool>>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(result); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/ProjectOneTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class ProjectOneTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, TestProjection>> projection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public void WithFilterAndProjection_Projects() { // Arrange var expected = Fixture.Create(); SetupReader(expected); // Act var result = Sut.ProjectOne(filter, projection); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne, TestProjection, int>( filter, projection, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupReader(expected); // Act var result = Sut.ProjectOne(filter, projection, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne, TestProjection, int>(filter, projection, null, token), Times.Once); } [Fact] public void WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(expected); // Act var result = Sut.ProjectOne(filter, projection, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne, TestProjection, int>(filter, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(expected); // Act var result = Sut.ProjectOne(filter, projection, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne, TestProjection, int>(filter, projection, partitionKey, token), Times.Once); } private void SetupReader(TestProjection result) { Reader = new Mock(); Reader .Setup( x => x.ProjectOne, TestProjection, int>( It.IsAny, bool>>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(result); } } ================================================ FILE: CoreUnitTests/KeyedReadOnlyMongoRepositoryTests/SumByAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.KeyedReadOnlyMongoRepositoryTests; public class SumByAsyncTests : TestKeyedReadOnlyMongoRepositoryContext { private readonly Expression, bool>> filter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> intSelector = document => document.SomeValue; private readonly Expression, decimal>> decimalSelector = document => document.SomeDecimalValue; [Fact] public async Task Int_WithFilterAndSelector_Sums() { // Arrange var expected = Fixture.Create(); SetupReaderInt(expected); // Act var result = await Sut.SumByAsync(filter, intSelector); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(filter, intSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Int_WithFilterAndSelectorAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupReaderInt(expected); // Act var result = await Sut.SumByAsync(filter, intSelector, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(filter, intSelector, null, token), Times.Once); } [Fact] public async Task Int_WithFilterAndSelectorAndPartitionKey_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReaderInt(expected); // Act var result = await Sut.SumByAsync(filter, intSelector, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(filter, intSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Int_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReaderInt(expected); // Act var result = await Sut.SumByAsync(filter, intSelector, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(filter, intSelector, partitionKey, token), Times.Once); } [Fact] public async Task Decimal_WithFilterAndSelector_Sums() { // Arrange var expected = Fixture.Create(); SetupReaderDecimal(expected); // Act var result = await Sut.SumByAsync(filter, decimalSelector); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(filter, decimalSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Decimal_WithFilterAndSelectorAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupReaderDecimal(expected); // Act var result = await Sut.SumByAsync(filter, decimalSelector, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(filter, decimalSelector, null, token), Times.Once); } [Fact] public async Task Decimal_WithFilterAndSelectorAndPartitionKey_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReaderDecimal(expected); // Act var result = await Sut.SumByAsync(filter, decimalSelector, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(filter, decimalSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Decimal_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReaderDecimal(expected); // Act var result = await Sut.SumByAsync(filter, decimalSelector, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(filter, decimalSelector, partitionKey, token), Times.Once); } private void SetupReaderInt(int expected) { Reader = new Mock(); Reader .Setup( x => x.SumByAsync, int>( It.IsAny, bool>>>(), It.IsAny,int>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(expected); } private void SetupReaderDecimal(decimal expected) { Reader = new Mock(); Reader .Setup( x => x.SumByAsync, int>( It.IsAny, bool>>>(), It.IsAny, decimal>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(expected); } } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/AnyAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class AnyAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> expression = document => document.SomeContent == "SomeContent"; private readonly Expression, bool>> keyedExpression = document => document.SomeContent == "SomeContent"; private readonly FilterDefinition> keyedFilter = Builders>.Filter.Eq(x => x.Id, 1); [Fact] public async Task WithExpression_GetsResult() { // Arrange SetupReader(); // Act var result = await Sut.AnyAsync(expression); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync(expression, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithExpressionAndCancellationToken_GetsResult() { // Arrange var token = new CancellationToken(true); SetupReader(); // Act var result = await Sut.AnyAsync(expression, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync(expression, null, token), Times.Once); } [Fact] public async Task WithExpressionAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); SetupReader(); // Act var result = await Sut.AnyAsync(expression, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync(expression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithExpressionAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(); // Act var result = await Sut.AnyAsync(expression, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync(expression, partitionKey, token), Times.Once); } #region keyed [Fact] public async Task Keyed_WithExpression_GetsResult() { // Arrange SetupKeyedReaderWithExpression(); // Act var result = await Sut.AnyAsync, int>(keyedExpression); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedExpression, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndCancellationToken_GetsResult() { // Arrange var token = new CancellationToken(true); SetupKeyedReaderWithExpression(); // Act var result = await Sut.AnyAsync, int>(keyedExpression, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedExpression, null, token), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); SetupKeyedReaderWithExpression(); // Act var result = await Sut.AnyAsync, int>(keyedExpression, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedExpression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithExpression(); // Act var result = await Sut.AnyAsync, int>(keyedExpression, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedExpression, partitionKey, token), Times.Once); } [Fact] public async Task Keyed_WithFilter_GetsResult() { // Arrange SetupKeyedReaderWithFilter(); // Act var result = await Sut.AnyAsync, int>(keyedFilter); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedFilter, null, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndOptions_GetsResult() { // Arrange var options = new CountOptions(); SetupKeyedReaderWithFilter(); // Act var result = await Sut.AnyAsync, int>(keyedFilter, options); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedFilter, options, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCancellationToken_GetsResult() { // Arrange var token = new CancellationToken(true); SetupKeyedReaderWithFilter(); // Act var result = await Sut.AnyAsync, int>(keyedFilter, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedFilter, null, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndOptionsAndCancellationToken_GetsResult() { // Arrange var token = new CancellationToken(true); var options = new CountOptions(); SetupKeyedReaderWithFilter(); // Act var result = await Sut.AnyAsync, int>(keyedFilter, options, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedFilter, options, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); SetupKeyedReaderWithFilter(); // Act var result = await Sut.AnyAsync, int>(keyedFilter, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedFilter, null, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCountOptionsAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var options = new CountOptions(); SetupKeyedReaderWithFilter(); // Act var result = await Sut.AnyAsync, int>(keyedFilter, options, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedFilter, options, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(); // Act var result = await Sut.AnyAsync, int>(keyedFilter, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedFilter, null, partitionKey, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCountOptionsAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var options = new CountOptions(); SetupKeyedReaderWithFilter(); // Act var result = await Sut.AnyAsync, int>(keyedFilter, options, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.AnyAsync, int>(keyedFilter, options, partitionKey, token), Times.Once); } private void SetupKeyedReaderWithExpression() { Reader = new Mock(); Reader .Setup( x => x.AnyAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); } private void SetupKeyedReaderWithFilter() { Reader = new Mock(); Reader .Setup( x => x.AnyAsync, int>( It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); } #endregion private void SetupReader() { Reader = new Mock(); Reader .Setup( x => x.AnyAsync( It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); } } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/AnyTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class AnyTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> expression = document => document.SomeContent == "SomeContent"; [Fact] public void WithExpression_GetsResult() { // Arrange SetupReader(); // Act var result = Sut.Any(expression); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any(expression, null, CancellationToken.None), Times.Once); } [Fact] public void WithExpressionAndCancellationToken_GetsResult() { // Arrange var token = new CancellationToken(true); SetupReader(); // Act var result = Sut.Any(expression, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any(expression, null, token), Times.Once); } [Fact] public void WithExpressionAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); SetupReader(); // Act var result = Sut.Any(expression, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any(expression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithExpressionAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(); // Act var result = Sut.Any(expression, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any(expression, partitionKey, token), Times.Once); } private void SetupReader() { Reader = new Mock(); Reader .Setup( x => x.Any( It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(true); } #region Keyed private readonly Expression, bool>> keyedExpression = document => document.SomeContent == "SomeContent"; private readonly FilterDefinition> keyedFilter = Builders>.Filter.Eq(document => document.SomeContent, "SomeContent"); [Fact] public void Keyed_WithExpression_GetsResult() { // Arrange SetupKeyedReaderWithExpression(); // Act var result = Sut.Any, int>(keyedExpression); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedExpression, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithExpressionAndCancellationToken_GetsResult() { // Arrange var token = new CancellationToken(true); SetupKeyedReaderWithExpression(); // Act var result = Sut.Any, int>(keyedExpression, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedExpression, null, token), Times.Once); } [Fact] public void Keyed_WithExpressionAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); SetupKeyedReaderWithExpression(); // Act var result = Sut.Any, int>(keyedExpression, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedExpression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithExpressionAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithExpression(); // Act var result = Sut.Any, int>(keyedExpression, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedExpression, partitionKey, token), Times.Once); } [Fact] public void Keyed_WithFilter_GetsResult() { // Arrange SetupKeyedReaderWithFilter(); // Act var result = Sut.Any, int>(keyedFilter); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedFilter, null, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndCancellationToken_GetsResult() { // Arrange var token = new CancellationToken(true); SetupKeyedReaderWithFilter(); // Act var result = Sut.Any, int>(keyedFilter, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedFilter, null, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndOptions_GetsResult() { // Arrange var options = new CountOptions(); SetupKeyedReaderWithFilter(); // Act var result = Sut.Any, int>(keyedFilter, options); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedFilter, options, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndOptionsAndCancellationToken_GetsResult() { // Arrange var options = new CountOptions(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(); // Act var result = Sut.Any, int>(keyedFilter, options, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedFilter, options, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); SetupKeyedReaderWithFilter(); // Act var result = Sut.Any, int>(keyedFilter, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedFilter, null, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndOptionsAndPartitionKey_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var options = new CountOptions(); SetupKeyedReaderWithFilter(); // Act var result = Sut.Any, int>(keyedFilter, options, partitionKey); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedFilter, options, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(); // Act var result = Sut.Any, int>(keyedFilter, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedFilter, null, partitionKey, token), Times.Once); } [Fact] public void Keyed_WithFilterAndOptionsAndPartitionKeyAndCancellationToken_GetsResult() { // Arrange var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var options = new CountOptions(); SetupKeyedReaderWithFilter(); // Act var result = Sut.Any, int>(keyedFilter, options, partitionKey, token); // Assert result.Should().BeTrue(); Reader.Verify( x => x.Any, int>(keyedFilter, options, partitionKey, token), Times.Once); } private void SetupKeyedReaderWithExpression() { Reader = new Mock(); Reader .Setup( x => x.Any, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(true); } private void SetupKeyedReaderWithFilter() { Reader = new Mock(); Reader .Setup( x => x.Any, int>( It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/CountAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class CountAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> expression = document => document.SomeContent == "SomeContent"; [Fact] public async Task WithExpression_Counts() { // Arrange var count = Fixture.Create(); SetupReader(count); // Act var result = await Sut.CountAsync(expression); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync(expression, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithExpressionAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); SetupReader(count); // Act var result = await Sut.CountAsync(expression, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync(expression, null, token), Times.Once); } [Fact] public async Task WithExpressionAndPartitionKey_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(count); // Act var result = await Sut.CountAsync(expression, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync(expression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithExpressionAndPartitionKeyAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(count); // Act var result = await Sut.CountAsync(expression, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync(expression, partitionKey, token), Times.Once); } private void SetupReader(long count) { Reader = new Mock(); Reader .Setup( x => x.CountAsync( It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); } #region Keyed private readonly Expression, bool>> keyedExpression = document => document.SomeContent == "SomeContent"; private readonly FilterDefinition> keyedFilter = Builders>.Filter.Eq(document => document.Id, 1); [Fact] public async Task Keyed_WithExpression_Counts() { // Arrange var count = Fixture.Create(); SetupKeyedReaderWithExpression(count); // Act var result = await Sut.CountAsync, int>(keyedExpression); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedExpression, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithExpression(count); // Act var result = await Sut.CountAsync, int>(keyedExpression, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedExpression, null, token), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndPartitionKey_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReaderWithExpression(count); // Act var result = await Sut.CountAsync, int>(keyedExpression, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedExpression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndPartitionKeyAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithExpression(count); // Act var result = await Sut.CountAsync, int>(keyedExpression, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedExpression, partitionKey, token), Times.Once); } [Fact] public async Task Keyed_WithFilter_Counts() { // Arrange var count = Fixture.Create(); SetupKeyedReaderWithFilter(count); // Act var result = await Sut.CountAsync, int>(keyedFilter); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedFilter, null, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCountOptions_Counts() { // Arrange var count = Fixture.Create(); var countOptions = new CountOptions(); SetupKeyedReaderWithFilter(count); // Act var result = await Sut.CountAsync, int>(keyedFilter, countOptions); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedFilter, countOptions, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(count); // Act var result = await Sut.CountAsync, int>(keyedFilter, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedFilter, null, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCountOptionsAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); var countOptions = new CountOptions(); SetupKeyedReaderWithFilter(count); // Act var result = await Sut.CountAsync, int>(keyedFilter, countOptions, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedFilter, countOptions, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKey_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReaderWithFilter(count); // Act var result = await Sut.CountAsync, int>(keyedFilter, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedFilter, null, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCountOptionsAndPartitionKey_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var countOptions = new CountOptions(); SetupKeyedReaderWithFilter(count); // Act var result = await Sut.CountAsync, int>(keyedFilter, countOptions, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedFilter, countOptions, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKeyAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(count); // Act var result = await Sut.CountAsync, int>(keyedFilter, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedFilter, null, partitionKey, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCountOptionsPartitionKeyAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var countOptions = new CountOptions(); SetupKeyedReaderWithFilter(count); // Act var result = await Sut.CountAsync, int>(keyedFilter, countOptions, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.CountAsync, int>(keyedFilter, countOptions, partitionKey, token), Times.Once); } private void SetupKeyedReaderWithExpression(long count) { Reader = new Mock(); Reader .Setup( x => x.CountAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); } private void SetupKeyedReaderWithFilter(long count) { Reader = new Mock(); Reader .Setup( x => x.CountAsync, int>( It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(count); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/CountTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class CountTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> expression = document => document.SomeContent == "SomeContent"; [Fact] public void WithExpression_Counts() { // Arrange var count = Fixture.Create(); SetupReader(count); // Act var result = Sut.Count(expression); // Assert result.Should().Be(count); Reader.Verify( x => x.Count(expression, null, CancellationToken.None), Times.Once); } [Fact] public void WithExpressionAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); SetupReader(count); // Act var result = Sut.Count(expression, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count(expression, null, token), Times.Once); } [Fact] public void WithExpressionAndPartitionKey_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(count); // Act var result = Sut.Count(expression, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.Count(expression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithExpressionAndPartitionKeyAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(count); // Act var result = Sut.Count(expression, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count(expression, partitionKey, token), Times.Once); } private void SetupReader(long count) { Reader = new Mock(); Reader .Setup( x => x.Count( It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(count); } #region Keyed private readonly Expression, bool>> keyedExpression = document => document.SomeContent == "SomeContent"; private readonly FilterDefinition> keyedFilter = Builders>.Filter.Eq( document => document.SomeContent, "SomeContent"); [Fact] public void Keyed_WithExpression_Counts() { // Arrange var count = Fixture.Create(); SetupKeyedReader(count); // Act var result = Sut.Count, int>(keyedExpression); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedExpression, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithExpressionAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(count); // Act var result = Sut.Count, int>(keyedExpression, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedExpression, null, token), Times.Once); } [Fact] public void Keyed_WithExpressionAndPartitionKey_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReader(count); // Act var result = Sut.Count, int>(keyedExpression, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedExpression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithExpressionAndPartitionKeyAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(count); // Act var result = Sut.Count, int>(keyedExpression, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedExpression, partitionKey, token), Times.Once); } private void SetupKeyedReader(long count) { Reader = new Mock(); Reader .Setup( x => x.Count, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(count); } [Fact] public void Keyed_WithFilter_Counts() { // Arrange var count = Fixture.Create(); SetupKeyedReaderWithFilter(count); // Act var result = Sut.Count, int>(keyedFilter); // Assert Reader.Verify( x => x.Count, int>(keyedFilter, null, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterAndCountOptions_Counts() { // Arrange var count = Fixture.Create(); var countOptions = new CountOptions(); SetupKeyedReaderWithFilter(count); // Act var result = Sut.Count, int>(keyedFilter, countOptions); // Assert Reader.Verify( x => x.Count, int>(keyedFilter, countOptions, null, CancellationToken.None), Times.Once); result.Should().Be(count); } [Fact] public void Keyed_WithFilterAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(count); // Act var result = Sut.Count, int>(keyedFilter, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedFilter, null, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndCountOptionsAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var token = new CancellationToken(true); var countOptions = new CountOptions(); SetupKeyedReaderWithFilter(count); // Act var result = Sut.Count, int>(keyedFilter, countOptions, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedFilter, countOptions, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKey_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReaderWithFilter(count); // Act var result = Sut.Count, int>(keyedFilter, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedFilter, null, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndCountOptionsAndPartitionKey_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var countOptions = new CountOptions(); SetupKeyedReaderWithFilter(count); // Act var result = Sut.Count, int>(keyedFilter, countOptions, partitionKey); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedFilter, countOptions, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKeyAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(count); // Act var result = Sut.Count, int>(keyedFilter, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedFilter, null, partitionKey, token), Times.Once); } [Fact] public void Keyed_WithFilterAndCountOptionsAndPartitionKeyAndCancellationToken_Counts() { // Arrange var count = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var countOptions = new CountOptions(); SetupKeyedReaderWithFilter(count); // Act var result = Sut.Count, int>(keyedFilter, countOptions, partitionKey, token); // Assert result.Should().Be(count); Reader.Verify( x => x.Count, int>(keyedFilter, countOptions, partitionKey, token), Times.Once); } private void SetupKeyedReaderWithFilter(long count) { Reader = new Mock(); Reader .Setup( x => x.Count, int>( It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(count); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetAllAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetAllAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> expression = document => document.SomeContent == "SomeContent"; [Fact] public async Task WithExpression_GetsAll() { // Arrange var document = Fixture.CreateMany().ToList(); SetupReader(document); // Act var result = await Sut.GetAllAsync(expression); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync(expression, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithExpressionAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetAllAsync(expression, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync(expression, null, token), Times.Once); } [Fact] public async Task WithExpressionAndPartitionKey_GetsAll() { // Arrange var document = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetAllAsync(expression, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync(expression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithExpressionAndPartitionKeyAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetAllAsync(expression, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync(expression, partitionKey, token), Times.Once); } private void SetupReader(List documents) { Reader = new Mock(); Reader .Setup( x => x.GetAllAsync( It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents); } #region Keyed private readonly Expression, bool>> keyedExpression = document => document.SomeContent == "SomeContent"; private readonly FilterDefinition> keyedFilter = Builders>.Filter.Eq(document => document.SomeContent, "SomeContent"); [Fact] public async Task Keyed_WithExpression_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); SetupReader(document); // Act var result = await Sut.GetAllAsync, int>(keyedExpression); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedExpression, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetAllAsync, int>(keyedExpression, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedExpression, null, token), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndPartitionKey_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetAllAsync, int>(keyedExpression, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedExpression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndPartitionKeyAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetAllAsync, int>(keyedExpression, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedExpression, partitionKey, token), Times.Once); } [Fact] public async Task Keyed_WithFilter_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); SetupReaderWithFilter(document); // Act var result = await Sut.GetAllAsync, int>(keyedFilter); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedFilter, null, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndOptions_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var options = new FindOptions(); SetupReaderWithFilter(document); // Act var result = await Sut.GetAllAsync, int>(keyedFilter, options); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedFilter, options, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); SetupReaderWithFilter(document); // Act var result = await Sut.GetAllAsync, int>(keyedFilter, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedFilter, null, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndFindOptionsAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); var options = new FindOptions(); SetupReaderWithFilter(document); // Act var result = await Sut.GetAllAsync, int>(keyedFilter, options, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedFilter, options, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKey_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); SetupReaderWithFilter(document); // Act var result = await Sut.GetAllAsync, int>(keyedFilter, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedFilter, null, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndFindOptionsAndPartitionKey_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var options = new FindOptions(); SetupReaderWithFilter(document); // Act var result = await Sut.GetAllAsync, int>(keyedFilter, options, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedFilter, options, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKeyAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReaderWithFilter(document); // Act var result = await Sut.GetAllAsync, int>(keyedFilter, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedFilter, null, partitionKey, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndFindOptionsAndPartitionKeyAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var options = new FindOptions(); SetupReaderWithFilter(document); // Act var result = await Sut.GetAllAsync, int>(keyedFilter, options, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAllAsync, int>(keyedFilter, options, partitionKey, token), Times.Once); } private void SetupReaderWithFilter(List> documents) { Reader = new Mock(); Reader .Setup( x => x.GetAllAsync, int>( It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents); } private void SetupReader(List> documents) { Reader = new Mock(); Reader .Setup( x => x.GetAllAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetAllTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetAllTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> expression = document => document.SomeContent == "SomeContent"; [Fact] public void WithExpression_GetsAll() { // Arrange var document = Fixture.CreateMany().ToList(); SetupReader(document); // Act var result = Sut.GetAll(expression); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll(expression, null, CancellationToken.None), Times.Once); } [Fact] public void WithExpressionAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetAll(expression, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll(expression, null, token), Times.Once); } [Fact] public void WithExpressionAndPartitionKey_GetsAll() { // Arrange var document = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetAll(expression, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll(expression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithExpressionAndPartitionKeyAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetAll(expression, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll(expression, partitionKey, token), Times.Once); } private void SetupReader(List documents) { Reader = new Mock(); Reader .Setup( x => x.GetAll( It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(documents); } #region Keyed private readonly Expression, bool>> keyedExpression = document => document.SomeContent == "SomeContent"; private readonly FilterDefinition> keyedFilter = Builders>.Filter.Eq(document => document.SomeContent, "SomeContent"); [Fact] public void Keyed_WithExpression_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); SetupKeyedReader(document); // Act var result = Sut.GetAll, int>(keyedExpression); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedExpression, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithExpressionAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = Sut.GetAll, int>(keyedExpression, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedExpression, null, token), Times.Once); } [Fact] public void Keyed_WithExpressionAndPartitionKey_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); SetupKeyedReader(document); // Act var result = Sut.GetAll, int>(keyedExpression, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedExpression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithExpressionAndPartitionKeyAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = Sut.GetAll, int>(keyedExpression, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedExpression, partitionKey, token), Times.Once); } [Fact] public void Keyed_WithFilter_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetAll, int>(keyedFilter); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedFilter, null, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndFindOptions_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetAll, int>(keyedFilter, options); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedFilter, options, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetAll, int>(keyedFilter, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedFilter, null, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndFindOptionsAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var token = new CancellationToken(true); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetAll, int>(keyedFilter, options, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedFilter, options, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKey_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetAll, int>(keyedFilter, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedFilter, null, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndFindOptionsAndPartitionKey_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetAll, int>(keyedFilter, options, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedFilter, options, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKeyAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetAll, int>(keyedFilter, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedFilter, null, partitionKey, token), Times.Once); } [Fact] public void Keyed_WithFilterAndFindOptionsAndPartitionKeyAndCancellationToken_GetsAll() { // Arrange var document = Fixture.CreateMany>().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetAll, int>(keyedFilter, options, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetAll, int>(keyedFilter, options, partitionKey, token), Times.Once); } private void SetupKeyedReaderWithFilter(List> documents) { Reader = new Mock(); Reader .Setup( x => x.GetAll, int>( It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(documents); } private void SetupKeyedReader(List> documents) { Reader = new Mock(); Reader .Setup( x => x.GetAll, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(documents); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetByIdAsyncTests.cs ================================================ using System; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetByIdAsyncTests : TestReadOnlyMongoRepositoryContext { [Fact] public async Task WithId_Gets() { // Arrange var document = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByIdAsync(document.Id); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync(document.Id, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithIdAndCancellationToken_Gets() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByIdAsync(document.Id, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync(document.Id, null, token), Times.Once); } [Fact] public async Task WithIdAndPartitionKey_Gets() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByIdAsync(document.Id, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync(document.Id, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithIdAndPartitionKeyAndCancellationToken_Gets() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByIdAsync(document.Id, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync(document.Id, partitionKey, token), Times.Once); } private void SetupReader(TestDocument document) { Reader = new Mock(); Reader .Setup( x => x.GetByIdAsync( It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } #region Keyed [Fact] public async Task Keyed_WithId_Gets() { // Arrange var document = Fixture.Create>(); SetupKeyedReader(document); // Act var result = await Sut.GetByIdAsync, int>(document.Id); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync, int>(document.Id, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithIdAndCancellationToken_Gets() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = await Sut.GetByIdAsync, int>(document.Id, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync, int>(document.Id, null, token), Times.Once); } [Fact] public async Task Keyed_WithIdAndPartitionKey_Gets() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupKeyedReader(document); // Act var result = await Sut.GetByIdAsync, int>(document.Id, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync, int>(document.Id, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithIdAndPartitionKeyAndCancellationToken_Gets() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = await Sut.GetByIdAsync, int>(document.Id, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByIdAsync, int>(document.Id, partitionKey, token), Times.Once); } private void SetupKeyedReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByIdAsync, int>( It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetByIdTests.cs ================================================ using System; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetByIdTests : TestReadOnlyMongoRepositoryContext { [Fact] public void WithId_Gets() { // Arrange var document = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetById(document.Id); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById(document.Id, null, CancellationToken.None), Times.Once); } [Fact] public void WithIdAndCancellationToken_Gets() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetById(document.Id, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById(document.Id, null, token), Times.Once); } [Fact] public void WithIdAndPartitionKey_Gets() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetById(document.Id, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById(document.Id, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithIdAndPartitionKeyAndCancellationToken_Gets() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetById(document.Id, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById(document.Id, partitionKey, token), Times.Once); } private void SetupReader(TestDocument document) { Reader = new Mock(); Reader .Setup( x => x.GetById( It.IsAny(), It.IsAny(), It.IsAny())) .Returns(document); } #region Keyed [Fact] public void Keyed_WithId_Gets() { // Arrange var document = Fixture.Create>(); SetupKeyedReader(document); // Act var result = Sut.GetById, int>(document.Id); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById, int>(document.Id, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithIdAndCancellationToken_Gets() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = Sut.GetById, int>(document.Id, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById, int>(document.Id, null, token), Times.Once); } [Fact] public void Keyed_WithIdAndPartitionKey_Gets() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupKeyedReader(document); // Act var result = Sut.GetById, int>(document.Id, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById, int>(document.Id, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithIdAndPartitionKeyAndCancellationToken_Gets() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = Sut.GetById, int>(document.Id, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetById, int>(document.Id, partitionKey, token), Times.Once); } private void SetupKeyedReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetById, int>( It.IsAny(), It.IsAny(), It.IsAny())) .Returns(document); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetByMaxAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetByMaxAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> selector = document => document.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByMaxAsync(filter, selector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMaxAsync(filter, selector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync(filter, selector, null, token), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByMaxAsync(filter, selector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMaxAsync(filter, selector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(TestDocument document) { Reader = new Mock(); Reader .Setup( x => x.GetByMaxAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, object>> keyedSelector = document => document.SomeValue; [Fact] public async Task Keyed_WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = await Sut.GetByMaxAsync, int>(keyedFilter, keyedSelector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync, int>(keyedFilter, keyedSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMaxAsync, int>(keyedFilter, keyedSelector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync, int>(keyedFilter, keyedSelector, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByMaxAsync, int>(keyedFilter, keyedSelector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync, int>(keyedFilter, keyedSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMaxAsync, int>(keyedFilter, keyedSelector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMaxAsync, int>(keyedFilter, keyedSelector, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByMaxAsync, int>( It.IsAny, bool>>>(), It.IsAny, object>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetByMaxTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetByMaxTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> selector = document => document.SomeValue; [Fact] public void WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetByMax(filter, selector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMax(filter, selector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax(filter, selector, null, token), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetByMax(filter, selector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMax(filter, selector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(TestDocument document) { Reader = new Mock(); Reader .Setup( x => x.GetByMax( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(document); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, object>> keyedSelector = document => document.SomeValue; [Fact] public void Keyed_WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = Sut.GetByMax, int>(keyedFilter, keyedSelector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax, int>(keyedFilter, keyedSelector, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMax, int>(keyedFilter, keyedSelector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax, int>(keyedFilter, keyedSelector, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetByMax, int>(keyedFilter, keyedSelector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax, int>(keyedFilter, keyedSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMax, int>(keyedFilter, keyedSelector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMax, int>(keyedFilter, keyedSelector, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByMax, int>( It.IsAny, bool>>>(), It.IsAny, object>>>(), It.IsAny(), It.IsAny())) .Returns(document); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetByMinAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetByMinAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> selector = document => document.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByMinAsync(filter, selector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMinAsync(filter, selector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync(filter, selector, null, token), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetByMinAsync(filter, selector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetByMinAsync(filter, selector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(TestDocument document) { Reader = new Mock(); Reader .Setup( x => x.GetByMinAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, object>> keyedSelector = document => document.SomeValue; [Fact] public async Task Keyed_WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create>(); SetupKeyedReader(document); // Act var result = await Sut.GetByMinAsync, int>(keyedFilter, keyedSelector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync, int>(keyedFilter, keyedSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = await Sut.GetByMinAsync, int>(keyedFilter, keyedSelector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync, int>(keyedFilter, keyedSelector, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupKeyedReader(document); // Act var result = await Sut.GetByMinAsync, int>(keyedFilter, keyedSelector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync, int>(keyedFilter, keyedSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = await Sut.GetByMinAsync, int>(keyedFilter, keyedSelector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMinAsync, int>(keyedFilter, keyedSelector, partitionKey, token), Times.Once); } private void SetupKeyedReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByMinAsync, int>( It.IsAny, bool>>>(), It.IsAny, object>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetByMinTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetByMinTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> selector = document => document.SomeValue; [Fact] public void WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetByMin(filter, selector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMin(filter, selector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin(filter, selector, null, token), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetByMin(filter, selector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMin(filter, selector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(TestDocument document) { Reader = new Mock(); Reader .Setup( x => x.GetByMin( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(document); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, object>> keyedSelector = document => document.SomeValue; [Fact] public void Keyed_WithFilterAndSelector_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = Sut.GetByMin, int>(keyedFilter, keyedSelector); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin, int>(keyedFilter, keyedSelector, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMin, int>(keyedFilter, keyedSelector, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin, int>(keyedFilter, keyedSelector, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetByMin, int>(keyedFilter, keyedSelector, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin, int>(keyedFilter, keyedSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetByMin, int>(keyedFilter, keyedSelector, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetByMin, int>(keyedFilter, keyedSelector, partitionKey, token), Times.Once); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetByMin, int>( It.IsAny, bool>>>(), It.IsAny, object>>>(), It.IsAny(), It.IsAny())) .Returns(document); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetMaxValueAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetMaxValueAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> selector = document => document.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsMaxValue() { // Arrange var value = Fixture.Create(); SetupReader(value); // Act var result = await Sut.GetMaxValueAsync(filter, selector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = await Sut.GetMaxValueAsync(filter, selector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync(filter, selector, null, token), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(value); // Act var result = await Sut.GetMaxValueAsync(filter, selector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = await Sut.GetMaxValueAsync(filter, selector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMaxValueAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(value); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> keyedSelector = document => document.SomeValue; [Fact] public async Task Keyed_WithFilterAndSelector_GetsMaxValue() { // Arrange var value = Fixture.Create(); SetupKeyedReader(value); // Act var result = await Sut.GetMaxValueAsync, int, int>(keyedFilter, keyedSelector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync, int, int>(keyedFilter, keyedSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(value); // Act var result = await Sut.GetMaxValueAsync, int, int>(keyedFilter, keyedSelector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync, int, int>(keyedFilter, keyedSelector, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndPartitionKey_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReader(value); // Act var result = await Sut.GetMaxValueAsync, int, int>(keyedFilter, keyedSelector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync, int, int>(keyedFilter, keyedSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(value); // Act var result = await Sut.GetMaxValueAsync, int, int>(keyedFilter, keyedSelector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValueAsync, int, int>(keyedFilter, keyedSelector, partitionKey, token), Times.Once); } private void SetupKeyedReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMaxValueAsync, int, int>( It.IsAny, bool>>>(), It.IsAny, int>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(value); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetMaxValueTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetMaxValueTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> selector = document => document.SomeValue; [Fact] public void WithFilterAndSelector_GetsMaxValue() { // Arrange var value = Fixture.Create(); SetupReader(value); // Act var result = Sut.GetMaxValue(filter, selector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = Sut.GetMaxValue(filter, selector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue(filter, selector, null, token), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(value); // Act var result = Sut.GetMaxValue(filter, selector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = Sut.GetMaxValue(filter, selector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMaxValue( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(value); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> keyedSelector = document => document.SomeValue; [Fact] public void Keyed_WithFilterAndSelector_GetsMaxValue() { // Arrange var value = Fixture.Create(); SetupKeyedReader(value); // Act var result = Sut.GetMaxValue, int, int>(keyedFilter, keyedSelector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue, int, int>(keyedFilter, keyedSelector, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(value); // Act var result = Sut.GetMaxValue, int, int>(keyedFilter, keyedSelector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue, int, int>(keyedFilter, keyedSelector, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndPartitionKey_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReader(value); // Act var result = Sut.GetMaxValue, int, int>(keyedFilter, keyedSelector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue, int, int>(keyedFilter, keyedSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(value); // Act var result = Sut.GetMaxValue, int, int>(keyedFilter, keyedSelector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMaxValue, int, int>(keyedFilter, keyedSelector, partitionKey, token), Times.Once); } private void SetupKeyedReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMaxValue, int, int>( It.IsAny, bool>>>(), It.IsAny, int>>>(), It.IsAny(), It.IsAny())) .Returns(value); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetMinValueAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetMinValueAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> selector = document => document.SomeValue; [Fact] public async Task WithFilterAndSelector_GetsMaxValue() { // Arrange var value = Fixture.Create(); SetupReader(value); // Act var result = await Sut.GetMinValueAsync(filter, selector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = await Sut.GetMinValueAsync(filter, selector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync(filter, selector, null, token), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKey_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(value); // Act var result = await Sut.GetMinValueAsync(filter, selector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = await Sut.GetMinValueAsync(filter, selector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMinValueAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(value); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> keyedSelector = document => document.SomeValue; [Fact] public async Task Keyed_WithFilterAndSelector_GetsMaxValue() { // Arrange var value = Fixture.Create(); SetupKeyedReader(value); // Act var result = await Sut.GetMinValueAsync, int, int>(keyedFilter, keyedSelector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync, int, int>(keyedFilter, keyedSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(value); // Act var result = await Sut.GetMinValueAsync, int, int>(keyedFilter, keyedSelector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync, int, int>(keyedFilter, keyedSelector, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndPartitionKey_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReader(value); // Act var result = await Sut.GetMinValueAsync, int, int>(keyedFilter, keyedSelector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync, int, int>(keyedFilter, keyedSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMaxValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(value); // Act var result = await Sut.GetMinValueAsync, int, int>(keyedFilter, keyedSelector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValueAsync, int, int>(keyedFilter, keyedSelector, partitionKey, token), Times.Once); } private void SetupKeyedReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMinValueAsync, int, int>( It.IsAny, bool>>>(), It.IsAny, int>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(value); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetMinValueTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetMinValueTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> selector = document => document.SomeValue; [Fact] public void WithFilterAndSelector_GetsMinValue() { // Arrange var value = Fixture.Create(); SetupReader(value); // Act var result = Sut.GetMinValue(filter, selector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue(filter, selector, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndCancellationToken_GetsMinValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = Sut.GetMinValue(filter, selector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue(filter, selector, null, token), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKey_GetsMinValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(value); // Act var result = Sut.GetMinValue(filter, selector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue(filter, selector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMinValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(value); // Act var result = Sut.GetMinValue(filter, selector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue(filter, selector, partitionKey, token), Times.Once); } private void SetupReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMinValue( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(value); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> keyedSelector = document => document.SomeValue; [Fact] public void Keyed_WithFilterAndSelector_GetsMinValue() { // Arrange var value = Fixture.Create(); SetupKeyedReader(value); // Act var result = Sut.GetMinValue, int, int>(keyedFilter, keyedSelector); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue, int, int>(keyedFilter, keyedSelector, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndCancellationToken_GetsMinValue() { // Arrange var value = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(value); // Act var result = Sut.GetMinValue, int, int>(keyedFilter, keyedSelector, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue, int, int>(keyedFilter, keyedSelector, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndPartitionKey_GetsMinValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReader(value); // Act var result = Sut.GetMinValue, int, int>(keyedFilter, keyedSelector, partitionKey); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue, int, int>(keyedFilter, keyedSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMinValue() { // Arrange var value = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(value); // Act var result = Sut.GetMinValue, int, int>(keyedFilter, keyedSelector, partitionKey, token); // Assert result.Should().Be(value); Reader.Verify( x => x.GetMinValue, int, int>(keyedFilter, keyedSelector, partitionKey, token), Times.Once); } private void SetupKeyedReader(int value) { Reader = new Mock(); Reader .Setup( x => x.GetMinValue, int, int>( It.IsAny, bool>>>(), It.IsAny, int>>>(), It.IsAny(), It.IsAny())) .Returns(value); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetOneAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> expression = document => document.SomeContent == "SomeContent"; [Fact] public async Task WithExpression_GetsOne() { // Arrange var document = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetOneAsync(expression); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync(expression, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithExpressionAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetOneAsync(expression, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync(expression, null, token), Times.Once); } [Fact] public async Task WithExpressionAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetOneAsync(expression, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync(expression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithExpressionAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetOneAsync(expression, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync(expression, partitionKey, token), Times.Once); } private void SetupReader(TestDocument document) { Reader = new Mock(); Reader .Setup( x => x.GetOneAsync( It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } #region Keyed private readonly Expression, bool>> keyedExpression = document => document.SomeContent == "SomeContent"; private readonly FilterDefinition> keyedFilter = Builders>.Filter.Eq(document => document.SomeContent, "SomeContent"); [Fact] public async Task Keyed_WithExpression_GetsOne() { // Arrange var document = Fixture.Create>(); SetupReader(document); // Act var result = await Sut.GetOneAsync, int>(keyedExpression); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedExpression, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetOneAsync, int>(keyedExpression, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedExpression, null, token), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = await Sut.GetOneAsync, int>(keyedExpression, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedExpression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithExpressionAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = await Sut.GetOneAsync, int>(keyedExpression, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedExpression, partitionKey, token), Times.Once); } [Fact] public async Task Keyed_WithFilter_GetsOne() { // Arrange var document = Fixture.Create>(); SetupKeyedReaderWithFilter(document); // Act var result = await Sut.GetOneAsync, int>(keyedFilter); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedFilter, null, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndFindOptions_GetsOne() { // Arrange var document = Fixture.Create>(); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = await Sut.GetOneAsync, int>(keyedFilter, options); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedFilter, options, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(document); // Act var result = await Sut.GetOneAsync, int>(keyedFilter, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedFilter, null, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndFindOptionsAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = await Sut.GetOneAsync, int>(keyedFilter, options, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedFilter, options, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupKeyedReaderWithFilter(document); // Act var result = await Sut.GetOneAsync, int>(keyedFilter, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedFilter,null, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndFindOptionsAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = await Sut.GetOneAsync, int>(keyedFilter, options, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedFilter,options, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(document); // Act var result = await Sut.GetOneAsync, int>(keyedFilter, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedFilter,null, partitionKey, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndFindOptionsAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = await Sut.GetOneAsync, int>(keyedFilter, options, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOneAsync, int>(keyedFilter,options, partitionKey, token), Times.Once); } private void SetupKeyedReaderWithFilter(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetOneAsync, int>( It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } private void SetupReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetOneAsync, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(document); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetOneTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetOneTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> expression = document => document.SomeContent == "SomeContent"; [Fact] public void WithExpression_GetsOne() { // Arrange var document = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetOne(expression); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne(expression, null, CancellationToken.None), Times.Once); } [Fact] public void WithExpressionAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetOne(expression, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne(expression, null, token), Times.Once); } [Fact] public void WithExpressionAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(document); // Act var result = Sut.GetOne(expression, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne(expression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithExpressionAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(document); // Act var result = Sut.GetOne(expression, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne(expression, partitionKey, token), Times.Once); } private void SetupReader(TestDocument document) { Reader = new Mock(); Reader .Setup( x => x.GetOne( It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(document); } #region Keyed private readonly Expression, bool>> keyedExpression = document => document.SomeContent == "SomeContent"; private readonly FilterDefinition> keyedFilter = Builders>.Filter.Eq(document => document.SomeContent, "SomeContent"); [Fact] public void Keyed_WithExpression_GetsOne() { // Arrange var document = Fixture.Create>(); SetupKeyedReader(document); // Act var result = Sut.GetOne, int>(keyedExpression); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedExpression, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithExpressionAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = Sut.GetOne, int>(keyedExpression, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedExpression, null, token), Times.Once); } [Fact] public void Keyed_WithExpressionAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupKeyedReader(document); // Act var result = Sut.GetOne, int>(keyedExpression, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedExpression, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithExpressionAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(document); // Act var result = Sut.GetOne, int>(keyedExpression, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedExpression, partitionKey, token), Times.Once); } [Fact] public void Keyed_WithFilter_GetsOne() { // Arrange var document = Fixture.Create>(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetOne, int>(keyedFilter); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedFilter, null, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndFindOptions_GetsOne() { // Arrange var document = Fixture.Create>(); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetOne, int>(keyedFilter, options); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedFilter, options, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetOne, int>(keyedFilter, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedFilter, null, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndFindOptionsAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var token = new CancellationToken(true); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetOne, int>(keyedFilter, options, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedFilter, options, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetOne, int>(keyedFilter, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedFilter, null, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndFindOptionsAndPartitionKey_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetOne, int>(keyedFilter, options, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedFilter, options, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetOne, int>(keyedFilter, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedFilter, null, partitionKey, token), Times.Once); } [Fact] public void Keyed_WithFilterAndFindOptionsAndPartitionKeyAndCancellationToken_GetsOne() { // Arrange var document = Fixture.Create>(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); var options = new FindOptions(); SetupKeyedReaderWithFilter(document); // Act var result = Sut.GetOne, int>(keyedFilter, options, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(document); Reader.Verify( x => x.GetOne, int>(keyedFilter, options, partitionKey, token), Times.Once); } private void SetupKeyedReader(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetOne, int>( It.IsAny, bool>>>(), It.IsAny(), It.IsAny())) .Returns(document); } private void SetupKeyedReaderWithFilter(TestDocumentWithKey document) { Reader = new Mock(); Reader .Setup( x => x.GetOne, int>( It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(document); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GetSortedPaginatedAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GetSortedPaginatedAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.GroupingKey == 1; private readonly Expression> selector = document => document.GroupingKey; private readonly SortDefinition sortDefinition = Builders.Sort.Ascending(document => document.GroupingKey); private const bool DefaultAscending = true; private const int DefaultSkipNumber = 0; private const int DefaultTakeNumber = 50; [Fact] public async Task WithFilterAndSortSelector_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector); // Assert VerifySelector(result, documents, DefaultAscending, DefaultSkipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndAscending_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var ascending = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, ascending); // Assert VerifySelector(result, documents, ascending, DefaultSkipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndSkipNumber_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var skipNumber = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, skipNumber: skipNumber); // Assert VerifySelector(result, documents, DefaultAscending, skipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndTakeNumber_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var ascending = Fixture.Create(); var takeNumber = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, ascending, takeNumber: takeNumber); // Assert VerifySelector(result, documents, ascending, DefaultSkipNumber, takeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndPartitionKey_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var partitionKey = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, partitionKey: partitionKey); // Assert VerifySelector(result, documents, DefaultAscending, DefaultSkipNumber, DefaultTakeNumber, partitionKey, CancellationToken.None); } [Fact] public async Task WithFilterAndSortSelectorAndCancellationToken_GetsResults() { // Arrange var documents = SetupReaderWithSortSelector(); var cancellationToken = new CancellationToken(true); // Act var result = await Sut.GetSortedPaginatedAsync(filter, selector, cancellationToken: cancellationToken); // Assert VerifySelector(result, documents, DefaultAscending, DefaultSkipNumber, DefaultTakeNumber, null, cancellationToken); } [Fact] public async Task WithFilterAndSortDefinition_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition); // Assert VerifyDefinition(result, documents, DefaultSkipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortDefinitionAndSkipNumber_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); var skipNumber = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition, skipNumber); // Assert VerifyDefinition(result, documents, skipNumber, DefaultTakeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortDefinitionAndTakeNumber_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); var takeNumber = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition, takeNumber: takeNumber); // Assert VerifyDefinition(result, documents, DefaultSkipNumber, takeNumber, null, CancellationToken.None); } [Fact] public async Task WithFilterAndSortDefinitionAndPartitionKey_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); var partitionKey = Fixture.Create(); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition, partitionKey: partitionKey); // Assert VerifyDefinition(result, documents, DefaultSkipNumber, DefaultTakeNumber, partitionKey, CancellationToken.None); } [Fact] public async Task WithFilterAndSortDefinitionAndCancellationToken_GetsResults() { // Arrange var documents = SetupReaderWithSortDefinition(); var token = new CancellationToken(true); // Act var result = await Sut.GetSortedPaginatedAsync(filter, sortDefinition, cancellationToken: token); // Assert VerifyDefinition(result, documents, DefaultSkipNumber, DefaultTakeNumber, null, token); } private List SetupReaderWithSortSelector() { var documents = Fixture.CreateMany().ToList(); Reader = new Mock(); Reader.Setup( x => x.GetSortedPaginatedAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents); return documents; } private void VerifySelector(List result, List documents, bool ascending, int skipNumber, int takeNumber, string partitionKey, CancellationToken cancellationToken) { result.Should().NotBeNull(); result.Should().BeEquivalentTo(documents); Reader.Verify( x => x.GetSortedPaginatedAsync( filter, selector, ascending, skipNumber, takeNumber, partitionKey, cancellationToken), Times.Once); } private List SetupReaderWithSortDefinition() { var documents = Fixture.CreateMany().ToList(); Reader = new Mock(); Reader.Setup( x => x.GetSortedPaginatedAsync( It.IsAny>>(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(documents); return documents; } private void VerifyDefinition(List result, List documents, int skipNumber, int takeNumber, string partitionKey, CancellationToken cancellationToken) { result.Should().NotBeNull(); result.Should().BeEquivalentTo(documents); Reader.Verify( x => x.GetSortedPaginatedAsync( filter, sortDefinition, skipNumber, takeNumber, partitionKey, cancellationToken), Times.Once); } } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/GroupByTests.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class GroupByTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> grouping = document => document.GroupingKey; private readonly Expression, TestProjection>> projection = documents => new TestProjection {Count = documents.Count()}; private readonly Expression> filter = document => document.GroupingKey == 1; [Fact] public void WithGroupingCriteriaAndProjection_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); Reader = new Mock(); Reader.Setup( x => x.GroupBy( It.IsAny>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(grouping, projection); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy(grouping, projection, null, CancellationToken.None), Times.Once); } [Fact] public void WithGroupingCriteriaAndProjectionAndCancellationToken_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Reader = new Mock(); Reader .Setup( x => x.GroupBy( It.IsAny>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(grouping, projection, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy(grouping, projection, null, token), Times.Once); } [Fact] public void WithGroupingCriteriaAndProjectionAndPartitionKey_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Reader = new Mock(); Reader .Setup( x => x.GroupBy( It.IsAny>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(grouping, projection, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy(grouping, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithGroupingCriteriaAndProjectionAndPartitionKeyAndCancellationToken_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Reader = new Mock(); Reader .Setup( x => x.GroupBy( It.IsAny>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(grouping, projection, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy(grouping, projection, partitionKey, token), Times.Once); } [Fact] public void WithFilterAndGroupingCriteriaAndProjection_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); Reader = new Mock(); Reader.Setup( x => x.GroupBy( It.IsAny>>(), It.IsAny>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(filter, grouping, projection); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy(filter, grouping, projection, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndGroupingCriteriaAndProjectionAndCancellationToken_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Reader = new Mock(); Reader.Setup( x => x.GroupBy( It.IsAny>>(), It.IsAny>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(filter, grouping, projection, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy(filter, grouping, projection, null, token), Times.Once); } [Fact] public void WithFilterAndGroupingCriteriaAndProjectionAndPartitionKey_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Reader = new Mock(); Reader.Setup( x => x.GroupBy( It.IsAny>>(), It.IsAny>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(filter, grouping, projection, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy(filter, grouping, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndGroupingCriteriaAndProjectionAndPartitionKeyAndCancellationToken_Groups() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Reader = new Mock(); Reader.Setup( x => x.GroupBy( It.IsAny>>(), It.IsAny>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(projections); // Act var result = Sut.GroupBy(filter, grouping, projection, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(projections); Reader.Verify( x => x.GroupBy(filter, grouping, projection, partitionKey, token), Times.Once); } #region Keyed private readonly Expression, int>> keyedGrouping = document => document.GroupingKey; private readonly Expression>, TestProjection>> keyedProjection = documents => new TestProjection {Count = documents.Count()}; private readonly Expression, bool>> keyedFilter = document => document.GroupingKey == 1; [Fact] public void Keyed_WithGroupingCriteriaAndProjection_Groups() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(keyedProjections); // Act var result = Sut.GroupBy, int, TestProjection, int>(keyedGrouping, keyedProjection); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(keyedProjections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(keyedGrouping, keyedProjection, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithGroupingCriteriaAndProjectionAndCancellationToken_Groups() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Reader = new Mock(); Reader .Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(keyedProjections); // Act var result = Sut.GroupBy, int, TestProjection, int>(keyedGrouping, keyedProjection, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(keyedProjections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(keyedGrouping, keyedProjection, null, token), Times.Once); } [Fact] public void Keyed_WithGroupingCriteriaAndProjectionAndPartitionKey_Groups() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Reader = new Mock(); Reader .Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(keyedProjections); // Act var result = Sut.GroupBy, int, TestProjection, int>(keyedGrouping, keyedProjection, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(keyedProjections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(keyedGrouping, keyedProjection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithGroupingCriteriaAndProjectionAndPartitionKeyAndCancellationToken_Groups() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Reader = new Mock(); Reader .Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(keyedProjections); // Act var result = Sut.GroupBy, int, TestProjection, int>(keyedGrouping, keyedProjection, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(keyedProjections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(keyedGrouping, keyedProjection, partitionKey, token), Times.Once); } [Fact] public void Keyed_WithFilterAndGroupingCriteriaAndProjection_Groups() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny,bool>>>(), It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(keyedProjections); // Act var result = Sut.GroupBy, int, TestProjection, int>(keyedFilter, keyedGrouping, keyedProjection); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(keyedProjections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(keyedFilter, keyedGrouping, keyedProjection, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndGroupingCriteriaAndProjectionAndCancellationToken_Groups() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny,bool>>>(), It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(keyedProjections); // Act var result = Sut.GroupBy, int, TestProjection, int>(keyedFilter, keyedGrouping, keyedProjection, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(keyedProjections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(keyedFilter, keyedGrouping, keyedProjection, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndGroupingCriteriaAndProjectionAndPartitionKey_Groups() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny,bool>>>(), It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(keyedProjections); // Act var result = Sut.GroupBy, int, TestProjection, int>(keyedFilter, keyedGrouping, keyedProjection, partitionKey); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(keyedProjections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(keyedFilter, keyedGrouping, keyedProjection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndGroupingCriteriaAndProjectionAndPartitionKeyAndCancellationToken_Groups() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); Reader = new Mock(); Reader.Setup( x => x.GroupBy, int, TestProjection, int>( It.IsAny,bool>>>(), It.IsAny, int>>>(), It.IsAny>, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(keyedProjections); // Act var result = Sut.GroupBy, int, TestProjection, int>(keyedFilter, keyedGrouping, keyedProjection, partitionKey, token); // Assert result.Should().NotBeNull(); result.Should().BeEquivalentTo(keyedProjections); Reader.Verify( x => x.GroupBy, int, TestProjection, int>(keyedFilter, keyedGrouping, keyedProjection, partitionKey, token), Times.Once); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/ProjectManyAsyncTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class ProjectManyAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> projection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public async Task WithFilterAndProjection_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); SetupReader(projections); // Act var result = await Sut.ProjectManyAsync(filter, projection); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync( filter, projection, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); SetupReader(projections); // Act var result = await Sut.ProjectManyAsync(filter, projection, token); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync(filter, projection, null, token), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); SetupReader(projections); // Act var result = await Sut.ProjectManyAsync(filter, projection, partitionKey); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync(filter, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(projections); // Act var result = await Sut.ProjectManyAsync(filter, projection, partitionKey, token); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync(filter, projection, partitionKey, token), Times.Once); } private void SetupReader(List projections) { Reader = new Mock(); Reader .Setup( x => x.ProjectManyAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(projections); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, TestProjection>> keyedProjection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public async Task Keyed_WithFilterAndProjection_Projects() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); SetupKeyedReader(keyedProjections); // Act var result = await Sut.ProjectManyAsync, TestProjection, int>(keyedFilter, keyedProjection); // Assert result.Should().OnlyContain(x => keyedProjections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync, TestProjection, int>( keyedFilter, keyedProjection, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); SetupKeyedReader(keyedProjections); // Act var result = await Sut.ProjectManyAsync, TestProjection, int>(keyedFilter, keyedProjection, token); // Assert result.Should().OnlyContain(x => keyedProjections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync, TestProjection, int>(keyedFilter, keyedProjection, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); SetupKeyedReader(keyedProjections); // Act var result = await Sut.ProjectManyAsync, TestProjection, int>(keyedFilter, keyedProjection, partitionKey); // Assert result.Should().OnlyContain(x => keyedProjections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(keyedProjections); // Act var result = await Sut.ProjectManyAsync, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, token); // Assert result.Should().OnlyContain(x => keyedProjections.Contains(x)); Reader.Verify( x => x.ProjectManyAsync, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, token), Times.Once); } private void SetupKeyedReader(List keyedProjections) { Reader = new Mock(); Reader .Setup( x => x.ProjectManyAsync, TestProjection, int>( It.IsAny, bool>>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(keyedProjections); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/ProjectManyTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class ProjectManyTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> projection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public void WithFilterAndProjection_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); SetupReader(projections); // Act var result = Sut.ProjectMany(filter, projection); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectMany( filter, projection, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); SetupReader(projections); // Act var result = Sut.ProjectMany(filter, projection, token); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectMany(filter, projection, null, token), Times.Once); } [Fact] public void WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); SetupReader(projections); // Act var result = Sut.ProjectMany(filter, projection, partitionKey); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectMany(filter, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var projections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(projections); // Act var result = Sut.ProjectMany(filter, projection, partitionKey, token); // Assert result.Should().OnlyContain(x => projections.Contains(x)); Reader.Verify( x => x.ProjectMany(filter, projection, partitionKey, token), Times.Once); } private void SetupReader(List projections) { Reader = new Mock(); Reader .Setup( x => x.ProjectMany( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(projections); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, TestProjection>> keyedProjection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public void Keyed_WithFilterAndProjection_Projects() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); SetupKeyedReader(keyedProjections); // Act var result = Sut.ProjectMany, TestProjection, int>(keyedFilter, keyedProjection); // Assert result.Should().OnlyContain(x => keyedProjections.Contains(x)); Reader.Verify( x => x.ProjectMany, TestProjection, int>( keyedFilter, keyedProjection, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var token = new CancellationToken(true); SetupKeyedReader(keyedProjections); // Act var result = Sut.ProjectMany, TestProjection, int>(keyedFilter, keyedProjection, token); // Assert result.Should().OnlyContain(x => keyedProjections.Contains(x)); Reader.Verify( x => x.ProjectMany, TestProjection, int>(keyedFilter, keyedProjection, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); SetupKeyedReader(keyedProjections); // Act var result = Sut.ProjectMany, TestProjection, int>(keyedFilter, keyedProjection, partitionKey); // Assert result.Should().OnlyContain(x => keyedProjections.Contains(x)); Reader.Verify( x => x.ProjectMany, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var keyedProjections = Fixture.CreateMany().ToList(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(keyedProjections); // Act var result = Sut.ProjectMany, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, token); // Assert result.Should().OnlyContain(x => keyedProjections.Contains(x)); Reader.Verify( x => x.ProjectMany, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, token), Times.Once); } private void SetupKeyedReader(List keyedProjections) { Reader = new Mock(); Reader .Setup( x => x.ProjectMany, TestProjection, int>( It.IsAny, bool>>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(keyedProjections); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/ProjectOneAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class ProjectOneAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> projection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public async Task WithFilterAndProjection_Projects() { // Arrange var expected = Fixture.Create(); SetupReader(expected); // Act var result = await Sut.ProjectOneAsync(filter, projection); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync( filter, projection, null, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupReader(expected); // Act var result = await Sut.ProjectOneAsync(filter, projection, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync(filter, projection, null, token), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(expected); // Act var result = await Sut.ProjectOneAsync(filter, projection, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync(filter, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(expected); // Act var result = await Sut.ProjectOneAsync(filter, projection, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync(filter, projection, partitionKey, token), Times.Once); } private void SetupReader(TestProjection result) { Reader = new Mock(); Reader .Setup( x => x.ProjectOneAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(result); } #region keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, TestProjection>> keyedProjection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public async Task Keyed_WithFilterAndProjection_Projects() { // Arrange var expected = Fixture.Create(); SetupKeyedReader(expected); // Act var result = await Sut.ProjectOneAsync, TestProjection, int>(keyedFilter, keyedProjection); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync, TestProjection, int>( keyedFilter, keyedProjection, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(expected); // Act var result = await Sut.ProjectOneAsync, TestProjection, int>(keyedFilter, keyedProjection, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync, TestProjection, int>(keyedFilter, keyedProjection, null, token), Times.Once); } [Fact] public async Task Keyed_WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReader(expected); // Act var result = await Sut.ProjectOneAsync, TestProjection, int>(keyedFilter, keyedProjection, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(expected); // Act var result = await Sut.ProjectOneAsync, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOneAsync, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, token), Times.Once); } private void SetupKeyedReader(TestProjection result) { Reader = new Mock(); Reader .Setup( x => x.ProjectOneAsync, TestProjection, int>( It.IsAny, bool>>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(result); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/ProjectOneTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class ProjectOneTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> projection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public void WithFilterAndProjection_Projects() { // Arrange var expected = Fixture.Create(); SetupReader(expected); // Act var result = Sut.ProjectOne(filter, projection); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne( filter, projection, null, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupReader(expected); // Act var result = Sut.ProjectOne(filter, projection, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne(filter, projection, null, token), Times.Once); } [Fact] public void WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReader(expected); // Act var result = Sut.ProjectOne(filter, projection, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne(filter, projection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReader(expected); // Act var result = Sut.ProjectOne(filter, projection, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne(filter, projection, partitionKey, token), Times.Once); } private void SetupReader(TestProjection result) { Reader = new Mock(); Reader .Setup( x => x.ProjectOne( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .Returns(result); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, TestProjection>> keyedProjection = document => new TestProjection {NestedData = document.Nested.SomeDate}; [Fact] public void Keyed_WithFilterAndProjection_Projects() { // Arrange var expected = Fixture.Create(); SetupKeyedReader(expected); // Act var result = Sut.ProjectOne, TestProjection, int>(keyedFilter, keyedProjection); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne, TestProjection, int>( keyedFilter, keyedProjection, null, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndProjectionAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(expected); // Act var result = Sut.ProjectOne, TestProjection, int>(keyedFilter, keyedProjection, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne, TestProjection, int>(keyedFilter, keyedProjection, null, token), Times.Once); } [Fact] public void Keyed_WithFilterAndProjectionAndPartitionKey_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReader(expected); // Act var result = Sut.ProjectOne, TestProjection, int>(keyedFilter, keyedProjection, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, CancellationToken.None), Times.Once); } [Fact] public void Keyed_WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReader(expected); // Act var result = Sut.ProjectOne, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.ProjectOne, TestProjection, int>(keyedFilter, keyedProjection, partitionKey, token), Times.Once); } private void SetupKeyedReader(TestProjection result) { Reader = new Mock(); Reader .Setup( x => x.ProjectOne, TestProjection, int>( It.IsAny, bool>>>(), It.IsAny, TestProjection>>>(), It.IsAny(), It.IsAny())) .Returns(result); } #endregion } ================================================ FILE: CoreUnitTests/ReadOnlyMongoRepositoryTests/SumByAsyncTests.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using AutoFixture; using CoreUnitTests.Infrastructure; using CoreUnitTests.Infrastructure.Model; using FluentAssertions; using MongoDbGenericRepository.DataAccess.Read; using Moq; using Xunit; namespace CoreUnitTests.ReadOnlyMongoRepositoryTests; public class SumByAsyncTests : TestReadOnlyMongoRepositoryContext { private readonly Expression> decimalSelector = document => document.SomeDecimalValue; private readonly Expression> filter = document => document.SomeContent == "SomeContent"; private readonly Expression> intSelector = document => document.SomeValue; [Fact] public async Task Int_WithFilterAndSelector_Sums() { // Arrange var expected = Fixture.Create(); SetupReaderInt(expected); // Act var result = await Sut.SumByAsync(filter, intSelector); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync(filter, intSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Int_WithFilterAndSelectorAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupReaderInt(expected); // Act var result = await Sut.SumByAsync(filter, intSelector, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync(filter, intSelector, null, token), Times.Once); } [Fact] public async Task Int_WithFilterAndSelectorAndPartitionKey_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReaderInt(expected); // Act var result = await Sut.SumByAsync(filter, intSelector, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync(filter, intSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Int_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReaderInt(expected); // Act var result = await Sut.SumByAsync(filter, intSelector, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync(filter, intSelector, partitionKey, token), Times.Once); } [Fact] public async Task Decimal_WithFilterAndSelector_Sums() { // Arrange var expected = Fixture.Create(); SetupReaderDecimal(expected); // Act var result = await Sut.SumByAsync(filter, decimalSelector); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync(filter, decimalSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Decimal_WithFilterAndSelectorAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupReaderDecimal(expected); // Act var result = await Sut.SumByAsync(filter, decimalSelector, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync(filter, decimalSelector, null, token), Times.Once); } [Fact] public async Task Decimal_WithFilterAndSelectorAndPartitionKey_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupReaderDecimal(expected); // Act var result = await Sut.SumByAsync(filter, decimalSelector, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync(filter, decimalSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Decimal_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupReaderDecimal(expected); // Act var result = await Sut.SumByAsync(filter, decimalSelector, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync(filter, decimalSelector, partitionKey, token), Times.Once); } private void SetupReaderInt(int expected) { Reader = new Mock(); Reader .Setup( x => x.SumByAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(expected); } private void SetupReaderDecimal(decimal expected) { Reader = new Mock(); Reader .Setup( x => x.SumByAsync( It.IsAny>>(), It.IsAny>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(expected); } #region Keyed private readonly Expression, bool>> keyedFilter = document => document.SomeContent == "SomeContent"; private readonly Expression, int>> keyedIntSelector = document => document.SomeValue; private readonly Expression, decimal>> keyedDecimalSelector = document => document.SomeDecimalValue; [Fact] public async Task Keyed_Int_WithFilterAndSelector_Sums() { // Arrange var expected = Fixture.Create(); SetupKeyedReaderInt(expected); // Act var result = await Sut.SumByAsync, int>(keyedFilter, keyedIntSelector); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(keyedFilter, keyedIntSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_Int_WithFilterAndSelectorAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderInt(expected); // Act var result = await Sut.SumByAsync, int>(keyedFilter, keyedIntSelector, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(keyedFilter, keyedIntSelector, null, token), Times.Once); } [Fact] public async Task Keyed_Int_WithFilterAndSelectorAndPartitionKey_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReaderInt(expected); // Act var result = await Sut.SumByAsync, int>(keyedFilter, keyedIntSelector, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(keyedFilter, keyedIntSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_Int_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderInt(expected); // Act var result = await Sut.SumByAsync, int>(keyedFilter, keyedIntSelector, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(keyedFilter, keyedIntSelector, partitionKey, token), Times.Once); } [Fact] public async Task Keyed_Decimal_WithFilterAndSelector_Sums() { // Arrange var expected = Fixture.Create(); SetupKeyedReaderDecimal(expected); // Act var result = await Sut.SumByAsync, int>(keyedFilter, keyedDecimalSelector); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(keyedFilter, keyedDecimalSelector, null, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_Decimal_WithFilterAndSelectorAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderDecimal(expected); // Act var result = await Sut.SumByAsync, int>(keyedFilter, keyedDecimalSelector, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(keyedFilter, keyedDecimalSelector, null, token), Times.Once); } [Fact] public async Task Keyed_Decimal_WithFilterAndSelectorAndPartitionKey_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); SetupKeyedReaderDecimal(expected); // Act var result = await Sut.SumByAsync, int>(keyedFilter, keyedDecimalSelector, partitionKey); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(keyedFilter, keyedDecimalSelector, partitionKey, CancellationToken.None), Times.Once); } [Fact] public async Task Keyed_Decimal_WithFilterAndSelectorAndPartitionKeyAndCancellationToken_Sums() { // Arrange var expected = Fixture.Create(); var partitionKey = Fixture.Create(); var token = new CancellationToken(true); SetupKeyedReaderDecimal(expected); // Act var result = await Sut.SumByAsync, int>(keyedFilter, keyedDecimalSelector, partitionKey, token); // Assert result.Should().Be(expected); Reader.Verify( x => x.SumByAsync, int>(keyedFilter, keyedDecimalSelector, partitionKey, token), Times.Once); } private void SetupKeyedReaderInt(int expected) { Reader = new Mock(); Reader .Setup( x => x.SumByAsync, int>( It.IsAny, bool>>>(), It.IsAny,int>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(expected); } private void SetupKeyedReaderDecimal(decimal expected) { Reader = new Mock(); Reader .Setup( x => x.SumByAsync, int>( It.IsAny, bool>>>(), It.IsAny, decimal>>>(), It.IsAny(), It.IsAny())) .ReturnsAsync(expected); } #endregion } ================================================ FILE: IntegrationTests/App.config ================================================  ================================================ FILE: IntegrationTests/CRUDObjectIdTests.cs ================================================ using IntegrationTests.Infrastructure; using MongoDB.Bson; using NUnit.Framework; namespace IntegrationTests { public class ObjectIdTestDocument : TestDoc { } [TestFixture] public class CRUDObjectIdTests : MongoDbTKeyDocumentTestBase { public override string GetClassName() { return "CRUDObjectIdTests"; } } } ================================================ FILE: IntegrationTests/CRUDPartitionedCollectionNameAttributeTests.cs ================================================ using IntegrationTests.Infrastructure; using MongoDB.Bson.Serialization.Attributes; using MongoDbGenericRepository.Attributes; using MongoDbGenericRepository.Models; using System; namespace IntegrationTests { [CollectionName("TestingCollectionNameAttributePartitionedTKey")] public class PartitionedCollectionNameDoc : TestDoc, IPartitionedDocument { public PartitionedCollectionNameDoc() { PartitionKey = "TestPartitionKey"; } public string PartitionKey { get; set; } } public class CRUDPartitionedCollectionNameAttributeTests : MongoDbDocumentTestBase { public override string GetClassName() { return "CRUDPartitionedCollectionNameAttributeTests"; } } } ================================================ FILE: IntegrationTests/CRUDPartitionedTests.cs ================================================ using IntegrationTests.Infrastructure; using MongoDbGenericRepository.Models; namespace IntegrationTests { public class PartitionedDoc : TestDoc, IPartitionedDocument { public PartitionedDoc() { PartitionKey = "TestPartitionKey"; } public string PartitionKey { get; set; } } public class CRUDPartitionedTests : MongoDbDocumentTestBase { public override string GetClassName() { return "CRUDPartitionedCollectionNameAttributeTests"; } } } ================================================ FILE: IntegrationTests/CRUDTKeyPartitionedCollectionNameAttributeTests.cs ================================================ using IntegrationTests.Infrastructure; using MongoDbGenericRepository.Attributes; using MongoDbGenericRepository.Models; using System; namespace IntegrationTests { [CollectionName("TestingCollectionNameAttributePartitionedTKey")] public class TKeyPartitionedCollectionNameDoc : TestDoc, IPartitionedDocument { public TKeyPartitionedCollectionNameDoc() { PartitionKey = "TestPartitionKey"; } public string PartitionKey { get; set; } } public class CRUDTKeyPartitionedCollectionNameAttributeTests : MongoDbTKeyDocumentTestBase { public override string GetClassName() { return "CRUDTKeyPartitionedCollectionNameAttributeTests"; } } } ================================================ FILE: IntegrationTests/CRUDTKeyPartitionedTests.cs ================================================ using IntegrationTests.Infrastructure; using MongoDB.Bson.Serialization.Attributes; using MongoDbGenericRepository.Models; using NUnit.Framework; using System; namespace IntegrationTests { public class PartitionedTKeyTestDocument : TestDoc, IPartitionedDocument { public PartitionedTKeyTestDocument() { PartitionKey = "TestPartitionKey"; } public string PartitionKey { get; set; } } [TestFixture] public class CRUDTKeyPartitionedTests : MongoDbTKeyDocumentTestBase { public override string GetClassName() { return "CRUDTKeyPartitionedTests"; } } } ================================================ FILE: IntegrationTests/CRUDTKeyTests.cs ================================================ using IntegrationTests.Infrastructure; using MongoDB.Bson.Serialization.Attributes; using MongoDbGenericRepository.Models; using NUnit.Framework; using System; namespace IntegrationTests { public class TKeyTestDocument : TestDoc { } [TestFixture] public class CRUDTKeyTests : MongoDbTKeyDocumentTestBase { public override string GetClassName() { return "CreateTKeyTests"; } } } ================================================ FILE: IntegrationTests/CRUDTests.cs ================================================ using IntegrationTests.Infrastructure; using NUnit.Framework; namespace IntegrationTests { public class TestDocument : TestDoc { } [TestFixture] public class CRUDTests : MongoDbDocumentTestBase { public override string GetClassName() { return "CRUDTests"; } } } ================================================ FILE: IntegrationTests/Infrastructure/BaseMongoDbRepositoryTests.cs ================================================ using MongoDbGenericRepository.Models; using NUnit.Framework; using System.Collections.Generic; using System.Configuration; namespace IntegrationTests.Infrastructure { public class BaseMongoDbRepositoryTests where T : class, new() { public T CreateTestDocument() { return new T(); } public List CreateTestDocuments(int numberOfDocumentsToCreate) { var docs = new List(); for(var i = 0; i < numberOfDocumentsToCreate; i++) { docs.Add(new T()); } return docs; } public BaseMongoDbRepositoryTests() { var type = CreateTestDocument(); if (type is IPartitionedDocument) { PartitionKey = ((IPartitionedDocument)type).PartitionKey; } } public string PartitionKey { get; set; } /// /// SUT: System Under Test /// protected static ITestRepository SUT { get; set; } [OneTimeSetUp] public void Init() { var connectionString = ConfigurationManager.ConnectionStrings["MongoDbTests"].ConnectionString; SUT = new TestRepository(connectionString, "MongoDbTests"); } [OneTimeTearDown] public void Cleanup() { // We drop the collection at the end of each test session. if (!string.IsNullOrEmpty(PartitionKey)) { SUT.DropTestCollection(PartitionKey); } else { SUT.DropTestCollection(); } } } } ================================================ FILE: IntegrationTests/Infrastructure/GlobalVariables.cs ================================================ using System; namespace IntegrationTests.Infrastructure { /// /// A class holding global variables. /// public static class GlobalVariables { /// /// A random number generator. /// public static Random Random = new Random(); } } ================================================ FILE: IntegrationTests/Infrastructure/ITestRepository.cs ================================================ using MongoDbGenericRepository; namespace IntegrationTests { public interface ITestRepository : IBaseMongoRepository { void DropTestCollection(); void DropTestCollection(string partitionKey); } } ================================================ FILE: IntegrationTests/Infrastructure/MongoDBDocumentTestBase.cs ================================================ using MongoDbGenericRepository.Models; using NUnit.Framework; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace IntegrationTests.Infrastructure { [TestFixture] public abstract class MongoDbDocumentTestBase where T: TestDoc, new() { public T CreateTestDocument() { return new T(); } public abstract string GetClassName(); public List CreateTestDocuments(int numberOfDocumentsToCreate) { var docs = new List(); for (var i = 0; i < numberOfDocumentsToCreate; i++) { docs.Add(new T()); } return docs; } /// /// The partition key for the collection, if any /// protected string PartitionKey { get; set; } /// /// the name of the test class /// protected string TestClassName { get; set; } /// /// The name of the document used for tests /// protected string DocumentTypeName { get; set; } /// /// SUT: System Under Test /// protected static ITestRepository SUT { get; set; } public MongoDbDocumentTestBase() { var type = CreateTestDocument(); DocumentTypeName = type.GetType().FullName; if (type is IPartitionedDocument) { PartitionKey = ((IPartitionedDocument)type).PartitionKey; } TestClassName = GetClassName(); } [OneTimeSetUp] public void Init() { var connectionString = ConfigurationManager.ConnectionStrings["MongoDbTests"].ConnectionString; SUT = new TestRepository(connectionString, "MongoDbTests"); } [OneTimeTearDown] public void Cleanup() { // We drop the collection at the end of each test session. if (!string.IsNullOrEmpty(PartitionKey)) { SUT.DropTestCollection(PartitionKey); } else { SUT.DropTestCollection(); } } #region Add [Test] public void AddOne() { // Arrange var document = new T(); // Act SUT.AddOne(document); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(document.Id)) : SUT.Count(e => e.Id.Equals(document.Id), PartitionKey); Assert.That(count, Is.EqualTo(1), GetTestName()); } [Test] public async Task AddOneAsync() { // Arrange var document = new T(); // Act await SUT.AddOneAsync(document); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? await SUT.CountAsync(e => e.Id.Equals(document.Id)) : await SUT.CountAsync(e => e.Id.Equals(document.Id), PartitionKey); Assert.That(count, Is.EqualTo(1), GetTestName()); } [Test] public void AddMany() { // Arrange var documents = new List { new T(), new T() }; // Act SUT.AddMany(documents); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id)) : SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); Assert.That(count, Is.EqualTo(2), GetTestName()); } [Test] public async Task AddManyAsync() { // Arrange var documents = new List { new T(), new T() }; // Act await SUT.AddManyAsync(documents); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? await SUT.CountAsync(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id)) : await SUT.CountAsync(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); Assert.That(count, Is.EqualTo(2), GetTestName()); } #endregion Add #region Read [Test] public async Task GetByIdAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.GetByIdAsync(document.Id, PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); } [Test] public void GetById() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.GetById(document.Id, PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); } [Test] public async Task GetOneAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.GetOneAsync(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); } [Test] public void GetOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.GetOne(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); } [Test] public void GetCursor() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var cursor = SUT.GetCursor(x => x.Id.Equals(document.Id), PartitionKey); var count = cursor.CountDocuments(); // Assert Assert.That(count, Is.EqualTo(1), GetTestName()); } [Test] public async Task AnyAsyncReturnsTrue() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.AnyAsync(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.EqualTo(true), GetTestName()); } [Test] public async Task AnyAsyncReturnsFalse() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.AnyAsync(x => x.Id.Equals(Guid.NewGuid()), PartitionKey); // Assert Assert.That(result, Is.EqualTo(false), GetTestName()); } [Test] public void AnyReturnsTrue() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.EqualTo(true), GetTestName()); } [Test] public void AnyReturnsFalse() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(x => x.Id.Equals(Guid.NewGuid()), PartitionKey); // Assert Assert.That(result, Is.EqualTo(false), GetTestName()); } [Test] public async Task GetAllAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); await SUT.AddManyAsync(documents); // Act var result = await SUT.GetAllAsync(x => x.SomeContent == content, PartitionKey); // Assert Assert.That(result.Count, Is.EqualTo(5), GetTestName()); } [Test] public void GetAll() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.GetAll(x => x.SomeContent == content, PartitionKey); // Assert Assert.That(result.Count, Is.EqualTo(5), GetTestName()); } [Test] public async Task CountAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); await SUT.AddManyAsync(documents); // Act var result = await SUT.CountAsync(x => x.SomeContent == content, PartitionKey); // Assert Assert.That(result, Is.EqualTo(5), GetTestName()); } [Test] public void Count() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.Count(x => x.SomeContent == content, PartitionKey); // Assert Assert.That(result, Is.EqualTo(5), GetTestName()); } #endregion Read #region Update [Test] public void UpdateOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); document.SomeContent = content; // Act var result = SUT.UpdateOne(document); // Assert Assert.That(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public async Task UpdateOneAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); var content = GetContent(); document.SomeContent = content; // Act var result = await SUT.UpdateOneAsync(document); // Assert Assert.That(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public void UpdateOneField() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = SUT.UpdateOne(document, x => x.SomeContent, content); // Assert Assert.That(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public async Task UpdateOneFieldAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); var content = GetContent(); // Act var result = await SUT.UpdateOneAsync(document, x => x.SomeContent, content); // Assert Assert.That(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public void UpdateOneFieldWithFilter() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = SUT.UpdateOne(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.That(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public async Task UpdateOneFieldWithFilterAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); var content = GetContent(); // Act var result = await SUT.UpdateOneAsync(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.That(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public async Task UpdateOneAsyncWithUpdateDefinition() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = MongoDB.Driver.Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); // Act var result = await SUT.UpdateOneAsync(document, updateDef); // Assert Assert.That(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null); Assert.That(updatedDocument.Children[0].Type, Is.EqualTo(childrenToAdd[0].Type), GetTestName()); Assert.That(updatedDocument.Children[0].Value, Is.EqualTo(childrenToAdd[0].Value), GetTestName()); Assert.That(updatedDocument.Children[1].Type, Is.EqualTo(childrenToAdd[1].Type), GetTestName()); Assert.That(updatedDocument.Children[1].Value, Is.EqualTo(childrenToAdd[1].Value), GetTestName()); } [Test] public void UpdateOneWithUpdateDefinition() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = MongoDB.Driver.Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); // Act var result = SUT.UpdateOne(document, updateDef); // Assert Assert.That(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null); Assert.That(updatedDocument.Children[0].Type, Is.EqualTo(childrenToAdd[0].Type), GetTestName()); Assert.That(updatedDocument.Children[0].Value, Is.EqualTo(childrenToAdd[0].Value), GetTestName()); Assert.That(updatedDocument.Children[1].Type, Is.EqualTo(childrenToAdd[1].Type), GetTestName()); Assert.That(updatedDocument.Children[1].Value, Is.EqualTo(childrenToAdd[1].Value), GetTestName()); } #endregion Update #region Delete [Test] public void DeleteOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.DeleteOne(document); // Assert Assert.That(result, Is.EqualTo(1)); Assert.That(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), Is.False, GetTestName()); } [Test] public void DeleteOneLinq() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.DeleteOne(e => e.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.EqualTo(1)); Assert.That(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), Is.False, GetTestName()); } [Test] public async Task DeleteOneAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.DeleteOneAsync(document); // Assert Assert.That(result, Is.EqualTo(1)); await Assert.ThatAsync(() => SUT.AnyAsync(e => e.Id.Equals(document.Id), PartitionKey), Is.False, GetTestName()); } [Test] public async Task DeleteOneAsyncLinq() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.DeleteOneAsync(e => e.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.EqualTo(1)); await Assert.ThatAsync(() => SUT.AnyAsync(e => e.Id.Equals(document.Id), PartitionKey), Is.False, GetTestName()); } [Test] public async Task DeleteManyAsyncLinq() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); await SUT.AddManyAsync(documents); // Act var result = await SUT.DeleteManyAsync(e => e.SomeContent == criteria, PartitionKey); // Assert Assert.That(result, Is.EqualTo(5)); await Assert.ThatAsync(() => SUT.AnyAsync(e => e.SomeContent == criteria, PartitionKey), Is.False, GetTestName()); } [Test] public async Task DeleteManyAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); await SUT.AddManyAsync(documents); // Act var result = await SUT.DeleteManyAsync(documents); // Assert Assert.That(result, Is.EqualTo(5)); await Assert.ThatAsync(() => SUT.AnyAsync(e => e.SomeContent == criteria, PartitionKey), Is.False, GetTestName()); } [Test] public void DeleteManyLinq() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); SUT.AddMany(documents); // Act var result = SUT.DeleteMany(e => e.SomeContent == criteria, PartitionKey); // Assert Assert.That(result, Is.EqualTo(5)); Assert.That(SUT.Any(e => e.SomeContent == criteria, PartitionKey), Is.False, GetTestName()); } [Test] public void DeleteMany() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); SUT.AddMany(documents); // Act var result = SUT.DeleteMany(documents); // Assert Assert.That(result, Is.EqualTo(5)); Assert.That(SUT.Any(e => e.SomeContent == criteria, PartitionKey), Is.False, GetTestName()); } #endregion Delete #region Project [Test] public async Task ProjectOneAsync() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var document = CreateTestDocument(); document.SomeContent = someContent; document.Nested.SomeDate = someDate; await SUT.AddOneAsync(document); // Act var result = await SUT.ProjectOneAsync( x => x.Id.Equals(document.Id), x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); Assert.That(result.SomeContent, Is.EqualTo(someContent), GetTestName()); Assert.That(result.SomeDate.Minute, Is.EqualTo(someDate.Minute), GetTestName()); Assert.That(result.SomeDate.Second, Is.EqualTo(someDate.Second), GetTestName()); } [Test] public void ProjectOne() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var document = CreateTestDocument(); document.SomeContent = someContent; document.Nested.SomeDate = someDate; SUT.AddOne(document); // Act var result = SUT.ProjectOne( x => x.Id.Equals(document.Id), x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); Assert.That(result.SomeContent, Is.EqualTo(someContent), GetTestName()); Assert.That(result.SomeDate.Minute, Is.EqualTo(someDate.Minute), GetTestName()); Assert.That(result.SomeDate.Second, Is.EqualTo(someDate.Second), GetTestName()); } [Test] public async Task ProjectManyAsync() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var documents = CreateTestDocuments(5); documents.ForEach(e => { e.SomeContent = someContent; e.Nested.SomeDate = someDate; }); await SUT.AddManyAsync(documents); // Act var result = await SUT.ProjectManyAsync( x => x.SomeContent == someContent, x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.That(result.Count, Is.EqualTo(5), GetTestName()); Assert.That(result.First().SomeContent, Is.EqualTo(someContent), GetTestName()); Assert.That(result.First().SomeDate.Minute, Is.EqualTo(someDate.Minute), GetTestName()); Assert.That(result.First().SomeDate.Second, Is.EqualTo(someDate.Second), GetTestName()); } [Test] public void ProjectMany() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var documents = CreateTestDocuments(5); documents.ForEach(e => { e.SomeContent = someContent; e.Nested.SomeDate = someDate; }); SUT.AddMany(documents); // Act var result = SUT.ProjectMany( x => x.SomeContent == someContent, x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.That(result.Count, Is.EqualTo(5), GetTestName()); Assert.That(result.First().SomeContent, Is.EqualTo(someContent), GetTestName()); Assert.That(result.First().SomeDate.Minute, Is.EqualTo(someDate.Minute), GetTestName()); Assert.That(result.First().SomeDate.Second, Is.EqualTo(someDate.Second), GetTestName()); } #endregion Project #region Group By [Test] public void GroupByTProjection() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); for (var i = 0; i < documents.Count - 2; i++) { documents[i].GroupingKey = 1; documents[i].SomeContent = $"{content}-{i}"; } for (var i = 3; i < documents.Count; i++) { documents[i].GroupingKey = 2; documents[i].SomeContent = $"{content}-{i}"; } SUT.AddMany(documents); // Act var result = SUT.GroupBy( e => e.GroupingKey, g => new ProjectedGroup { Key = g.Key, Content = g.Select(doc => doc.SomeContent).ToList() }, PartitionKey); // Assert var key1Group = result.First(e => e.Key == 1); Assert.That(key1Group, Is.Not.Null); Assert.That(key1Group.Content, Has.Count.EqualTo(3)); var key2Group = result.First(e => e.Key == 2); Assert.That(key2Group, Is.Not.Null); Assert.That(key2Group.Content, Has.Count.EqualTo(2)); } [Test] public void FilteredGroupByTProjection() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); for (var i = 0; i < documents.Count - 2; i++) { documents[i].GroupingKey = 4; documents[i].SomeContent = $"{content}-{i}"; } for (var i = 3; i < documents.Count; i++) { documents[i].GroupingKey = 5; documents[i].SomeContent = $"{content}-{i}"; } var guid1 = Guid.NewGuid().ToString("n"); var guid2 = Guid.NewGuid().ToString("n"); for (var i = 0; i < documents.Count - 1; i++) { documents[i].Children = new List { new Child(guid1, guid2) }; } SUT.AddMany(documents); // Act var result = SUT.GroupBy( e => e.Children.Any(c => c.Type == guid1), e => e.GroupingKey, g => new ProjectedGroup { Key = g.Key, Content = g.Select(doc => doc.SomeContent).ToList() }, PartitionKey); // Assert var key1Group = result.First(e => e.Key == 4); Assert.That(key1Group, Is.Not.Null); Assert.That(key1Group.Content, Has.Count.EqualTo(3)); var key2Group = result.First(e => e.Key == 5); Assert.That(key2Group, Is.Not.Null); Assert.That(key2Group.Content, Has.Count.EqualTo(1)); } #endregion Group By #region Test Utils [MethodImpl(MethodImplOptions.NoInlining)] private string GetCurrentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(1); return sf.GetMethod().Name; } [MethodImpl(MethodImplOptions.NoInlining)] private string GetParentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(2); var method = sf.GetMethod().DeclaringType.Name; return method; } private string GetTestName() { return $"{TestClassName}{PartitionKey}.{GetParentMethod()}"; } private string GetContent() { return $"{TestClassName}{PartitionKey}.{Guid.NewGuid()}.{GetParentMethod()}"; } #endregion Test Utils } } ================================================ FILE: IntegrationTests/Infrastructure/MongoDbTKeyDocumentTestBase.cs ================================================ using MongoDbGenericRepository.Models; using NUnit.Framework; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace IntegrationTests.Infrastructure { [TestFixture] public abstract class MongoDbTKeyDocumentTestBase where T: TestDoc, new() where TKey : IEquatable { public T CreateTestDocument() { return new T(); } public abstract string GetClassName(); public List CreateTestDocuments(int numberOfDocumentsToCreate) { var docs = new List(); for (var i = 0; i < numberOfDocumentsToCreate; i++) { docs.Add(new T()); } return docs; } /// /// The partition key for the collection, if any /// protected string PartitionKey { get; set; } /// /// the name of the test class /// protected string TestClassName { get; set; } /// /// The name of the document used for tests /// protected string DocumentTypeName { get; set; } /// /// SUT: System Under Test /// protected static ITestRepository SUT { get; set; } public MongoDbTKeyDocumentTestBase() { var type = CreateTestDocument(); DocumentTypeName = type.GetType().FullName; if (type is IPartitionedDocument) { PartitionKey = ((IPartitionedDocument)type).PartitionKey; } TestClassName = GetClassName(); } [OneTimeSetUp] public void Init() { var connectionString = ConfigurationManager.ConnectionStrings["MongoDbTests"].ConnectionString; SUT = new TestRepository(connectionString, "MongoDbTests"); } [OneTimeTearDown] public void Cleanup() { // We drop the collection at the end of each test session. if (!string.IsNullOrEmpty(PartitionKey)) { SUT.DropTestCollection(PartitionKey); } else { SUT.DropTestCollection(); } } #region Add [Test] public void AddOne() { // Arrange var document = new T(); // Act SUT.AddOne(document); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(document.Id)) : SUT.Count(e => e.Id.Equals(document.Id), PartitionKey); Assert.That(count, Is.EqualTo(1), GetTestName()); } [Test] public async Task AddOneAsync() { // Arrange var document = new T(); // Act await SUT.AddOneAsync(document); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? await SUT.CountAsync(e => e.Id.Equals(document.Id)) : await SUT.CountAsync(e => e.Id.Equals(document.Id), PartitionKey); Assert.That(count, Is.EqualTo(1), GetTestName()); } [Test] public void AddMany() { // Arrange var documents = new List { new T(), new T() }; // Act SUT.AddMany(documents); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id)) : SUT.Count(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); Assert.That(count, Is.EqualTo(2), GetTestName()); } [Test] public async Task AddManyAsync() { // Arrange var documents = new List { new T(), new T() }; // Act await SUT.AddManyAsync(documents); // Assert long count = string.IsNullOrEmpty(PartitionKey) ? await SUT.CountAsync(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id)) : await SUT.CountAsync(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey); Assert.That(count, Is.EqualTo(2), GetTestName()); } #endregion Add #region Read [Test] public async Task GetByIdAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.GetByIdAsync(document.Id, PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); } [Test] public void GetById() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.GetById(document.Id, PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); } [Test] public async Task GetOneAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.GetOneAsync(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); } [Test] public void GetOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.GetOne(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); } [Test] public void GetCursor() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var cursor = SUT.GetCursor(x => x.Id.Equals(document.Id), PartitionKey); var count = cursor.CountDocuments(); // Assert Assert.That(count, Is.EqualTo(1), GetTestName()); } [Test] public async Task AnyAsyncReturnsTrue() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.AnyAsync(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.EqualTo(true), GetTestName()); } [Test] public async Task AnyAsyncReturnsFalse() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.AnyAsync(x => x.Id.Equals(document.Init()), PartitionKey); // Assert Assert.That(result, Is.EqualTo(false), GetTestName()); } [Test] public void AnyReturnsTrue() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(x => x.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.EqualTo(true), GetTestName()); } [Test] public void AnyReturnsFalse() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.Any(x => x.Id.Equals(document.Init()), PartitionKey); // Assert Assert.That(result, Is.EqualTo(false), GetTestName()); } [Test] public async Task GetAllAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); await SUT.AddManyAsync(documents); // Act var result = await SUT.GetAllAsync(x => x.SomeContent == content, PartitionKey); // Assert Assert.That(result.Count, Is.EqualTo(5), GetTestName()); } [Test] public void GetAll() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.GetAll(x => x.SomeContent == content, PartitionKey); // Assert Assert.That(result.Count, Is.EqualTo(5), GetTestName()); } [Test] public async Task CountAsync() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); await SUT.AddManyAsync(documents); // Act var result = await SUT.CountAsync(x => x.SomeContent == content, PartitionKey); // Assert Assert.That(result, Is.EqualTo(5), GetTestName()); } [Test] public void Count() { // Arrange var documents = CreateTestDocuments(5); var content = GetContent(); documents.ForEach(e => e.SomeContent = content); SUT.AddMany(documents); // Act var result = SUT.Count(x => x.SomeContent == content, PartitionKey); // Assert Assert.That(result, Is.EqualTo(5), GetTestName()); } #endregion Read #region Update [Test] public void UpdateOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); document.SomeContent = content; // Act var result = SUT.UpdateOne(document); // Assert Assert.That(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public async Task UpdateOneAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); var content = GetContent(); document.SomeContent = content; // Act var result = await SUT.UpdateOneAsync(document); // Assert Assert.That(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public void UpdateOneField() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = SUT.UpdateOne(document, x => x.SomeContent, content); // Assert Assert.That(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public async Task UpdateOneFieldAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); var content = GetContent(); // Act var result = await SUT.UpdateOneAsync(document, x => x.SomeContent, content); // Assert Assert.That(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public void UpdateOneFieldWithFilter() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var content = GetContent(); // Act var result = SUT.UpdateOne(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.That(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public async Task UpdateOneFieldWithFilterAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); var content = GetContent(); // Act var result = await SUT.UpdateOneAsync(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey); // Assert Assert.That(result, GetTestName()); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null, GetTestName()); Assert.That(updatedDocument.SomeContent, Is.EqualTo(content), GetTestName()); } [Test] public async Task UpdateOneAsyncWithUpdateDefinition() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = MongoDB.Driver.Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); // Act var result = await SUT.UpdateOneAsync(document, updateDef); // Assert Assert.That(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null); Assert.That(updatedDocument.Children[0].Type, Is.EqualTo(childrenToAdd[0].Type), GetTestName()); Assert.That(updatedDocument.Children[0].Value, Is.EqualTo(childrenToAdd[0].Value), GetTestName()); Assert.That(updatedDocument.Children[1].Type, Is.EqualTo(childrenToAdd[1].Type), GetTestName()); Assert.That(updatedDocument.Children[1].Value, Is.EqualTo(childrenToAdd[1].Value), GetTestName()); } [Test] public void UpdateOneWithUpdateDefinition() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); var childrenToAdd = new List { new Child("testType1", "testValue1"), new Child("testType2", "testValue2") }; var updateDef = MongoDB.Driver.Builders.Update.AddToSetEach(p => p.Children, childrenToAdd); // Act var result = SUT.UpdateOne(document, updateDef); // Assert Assert.That(result); var updatedDocument = SUT.GetById(document.Id, PartitionKey); Assert.That(updatedDocument, Is.Not.Null); Assert.That(updatedDocument.Children[0].Type, Is.EqualTo(childrenToAdd[0].Type), GetTestName()); Assert.That(updatedDocument.Children[0].Value, Is.EqualTo(childrenToAdd[0].Value), GetTestName()); Assert.That(updatedDocument.Children[1].Type, Is.EqualTo(childrenToAdd[1].Type), GetTestName()); Assert.That(updatedDocument.Children[1].Value, Is.EqualTo(childrenToAdd[1].Value), GetTestName()); } #endregion Update #region Delete [Test] public void DeleteOne() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.DeleteOne(document); // Assert Assert.That(result, Is.EqualTo(1)); Assert.That(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), Is.False, GetTestName()); } [Test] public void DeleteOneLinq() { // Arrange var document = CreateTestDocument(); SUT.AddOne(document); // Act var result = SUT.DeleteOne(e => e.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.EqualTo(1)); Assert.That(SUT.Any(e => e.Id.Equals(document.Id), PartitionKey), Is.False, GetTestName()); } [Test] public async Task DeleteOneAsync() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.DeleteOneAsync(document); // Assert Assert.That(result, Is.EqualTo(1)); await Assert.ThatAsync(() => SUT.AnyAsync(e => e.Id.Equals(document.Id), PartitionKey), Is.False, GetTestName()); } [Test] public async Task DeleteOneAsyncLinq() { // Arrange var document = CreateTestDocument(); await SUT.AddOneAsync(document); // Act var result = await SUT.DeleteOneAsync(e => e.Id.Equals(document.Id), PartitionKey); // Assert Assert.That(result, Is.EqualTo(1)); await Assert.ThatAsync(() => SUT.AnyAsync(e => e.Id.Equals(document.Id), PartitionKey), Is.False, GetTestName()); } [Test] public async Task DeleteManyAsyncLinq() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); await SUT.AddManyAsync(documents); // Act var result = await SUT.DeleteManyAsync(e => e.SomeContent == criteria, PartitionKey); // Assert Assert.That(result, Is.EqualTo(5)); await Assert.ThatAsync(() => SUT.AnyAsync(e => e.SomeContent == criteria, PartitionKey), Is.False, GetTestName()); } [Test] public async Task DeleteManyAsync() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); await SUT.AddManyAsync(documents); // Act var result = await SUT.DeleteManyAsync(documents); // Assert Assert.That(result, Is.EqualTo(5)); await Assert.ThatAsync(() => SUT.AnyAsync(e => e.SomeContent == criteria, PartitionKey), Is.False, GetTestName()); } [Test] public void DeleteManyLinq() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); SUT.AddMany(documents); // Act var result = SUT.DeleteMany(e => e.SomeContent == criteria, PartitionKey); // Assert Assert.That(result, Is.EqualTo(5)); Assert.That(SUT.Any(e => e.SomeContent == criteria, PartitionKey), Is.False, GetTestName()); } [Test] public void DeleteMany() { // Arrange var criteria = $"{GetTestName()}.{DocumentTypeName}"; var documents = CreateTestDocuments(5); documents.ForEach(e => e.SomeContent = criteria); SUT.AddMany(documents); // Act var result = SUT.DeleteMany(documents); // Assert Assert.That(result, Is.EqualTo(5)); Assert.That(SUT.Any(e => e.SomeContent == criteria, PartitionKey), Is.False, GetTestName()); } #endregion Delete #region Project [Test] public async Task ProjectOneAsync() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var document = CreateTestDocument(); document.SomeContent = someContent; document.Nested.SomeDate = someDate; await SUT.AddOneAsync(document); // Act var result = await SUT.ProjectOneAsync( x => x.Id.Equals(document.Id), x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); Assert.That(result.SomeContent, Is.EqualTo(someContent), GetTestName()); Assert.That(result.SomeDate.Minute, Is.EqualTo(someDate.Minute), GetTestName()); Assert.That(result.SomeDate.Second, Is.EqualTo(someDate.Second), GetTestName()); } [Test] public void ProjectOne() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var document = CreateTestDocument(); document.SomeContent = someContent; document.Nested.SomeDate = someDate; SUT.AddOne(document); // Act var result = SUT.ProjectOne( x => x.Id.Equals(document.Id), x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.That(result, Is.Not.Null, GetTestName()); Assert.That(result.SomeContent, Is.EqualTo(someContent), GetTestName()); Assert.That(result.SomeDate.Minute, Is.EqualTo(someDate.Minute), GetTestName()); Assert.That(result.SomeDate.Second, Is.EqualTo(someDate.Second), GetTestName()); } [Test] public async Task ProjectManyAsync() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var documents = CreateTestDocuments(5); documents.ForEach(e => { e.SomeContent = someContent; e.Nested.SomeDate = someDate; }); await SUT.AddManyAsync(documents); // Act var result = await SUT.ProjectManyAsync( x => x.SomeContent == someContent, x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.That(result.Count, Is.EqualTo(5), GetTestName()); Assert.That(result.First().SomeContent, Is.EqualTo(someContent), GetTestName()); Assert.That(result.First().SomeDate.Minute, Is.EqualTo(someDate.Minute), GetTestName()); Assert.That(result.First().SomeDate.Second, Is.EqualTo(someDate.Second), GetTestName()); } [Test] public void ProjectMany() { // Arrange var someContent = GetContent(); var someDate = DateTime.UtcNow; var documents = CreateTestDocuments(5); documents.ForEach(e => { e.SomeContent = someContent; e.Nested.SomeDate = someDate; }); SUT.AddMany(documents); // Act var result = SUT.ProjectMany( x => x.SomeContent == someContent, x => new MyTestProjection { SomeContent = x.SomeContent, SomeDate = x.Nested.SomeDate }, PartitionKey); // Assert Assert.That(result.Count, Is.EqualTo(5), GetTestName()); Assert.That(result.First().SomeContent, Is.EqualTo(someContent), GetTestName()); Assert.That(result.First().SomeDate.Minute, Is.EqualTo(someDate.Minute), GetTestName()); Assert.That(result.First().SomeDate.Second, Is.EqualTo(someDate.Second), GetTestName()); } #endregion Project #region Test Utils [MethodImpl(MethodImplOptions.NoInlining)] private string GetCurrentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(1); return sf.GetMethod().Name; } [MethodImpl(MethodImplOptions.NoInlining)] private string GetParentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(2); var method = sf.GetMethod().DeclaringType.Name; return method; } private string GetTestName() { return $"{TestClassName}{PartitionKey}.{GetParentMethod()}"; } private string GetContent() { return $"{TestClassName}{PartitionKey}.{Guid.NewGuid()}.{GetParentMethod()}"; } #endregion Test Utils } } ================================================ FILE: IntegrationTests/Infrastructure/RandomExtensions.cs ================================================ using System; namespace IntegrationTests.Infrastructure { // Thanks BlueRaja - Danny Pflughoeft https://stackoverflow.com/a/13095144/5103354 /// /// Extensions for the random number generator /// public static class RandomExtensions { /// /// Returns a random long from min (inclusive) to max (exclusive) /// /// The given random instance /// The inclusive minimum bound /// The exclusive maximum bound. Must be greater than min public static long NextLong(this Random random, long min, long max) { if (max <= min) throw new ArgumentOutOfRangeException("max", "max must be > min!"); //Working with ulong so that modulo works correctly with values > long.MaxValue ulong uRange = (ulong)(max - min); //Prevent a modulo bias; see https://stackoverflow.com/a/10984975/238419 //for more information. //In the worst case, the expected number of calls is 2 (though usually it's //much closer to 1) so this loop doesn't really hurt performance at all. ulong ulongRand; do { byte[] buf = new byte[8]; random.NextBytes(buf); ulongRand = (ulong)BitConverter.ToInt64(buf, 0); } while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange); return (long)(ulongRand % uRange) + min; } /// /// Returns a random long from 0 (inclusive) to max (exclusive) /// /// The given random instance /// The exclusive maximum bound. Must be greater than 0 public static long NextLong(this Random random, long max) { return random.NextLong(0, max); } /// /// Returns a random long over all possible values of long (except long.MaxValue, similar to /// random.Next()) /// /// The given random instance public static long NextLong(this Random random) { return random.NextLong(long.MinValue, long.MaxValue); } } } ================================================ FILE: IntegrationTests/Infrastructure/TestClasses.cs ================================================ using MongoDB.Bson.Serialization.Attributes; using MongoDbGenericRepository.Models; using MongoDbGenericRepository.Utils; using System; using System.Collections.Generic; namespace IntegrationTests.Infrastructure { public class ProjectedGroup { public int Key { get; set; } public List Content { get; set; } } public class MyTestProjection { public string SomeContent { get; set; } public DateTime SomeDate { get; set; } } public class Nested { public DateTime SomeDate { get; set; } } public class Child { public Child(string type, string value) { Type = type; Value = value; } public string Type { get; set; } public string Value { get; set; } } public class TestDoc : Document { public TestDoc() { Version = 2; Nested = new Nested { SomeDate = DateTime.UtcNow }; Children = new List(); } public string SomeContent { get; set; } public int GroupingKey { get; set; } public Nested Nested { get; set; } public List Children { get; set; } } public class TestDoc : IDocument where TKey : IEquatable { [BsonId] public TKey Id { get; set; } public int Version { get; set; } public TestDoc() { InitializeFields(); Version = 2; Nested = new Nested { SomeDate = DateTime.UtcNow }; Children = new List(); } public string SomeContent { get; set; } public Nested Nested { get; set; } public List Children { get; set; } public TId Init() { return IdGenerator.GetId(); } private void InitializeFields() { Id = Init(); } } } ================================================ FILE: IntegrationTests/Infrastructure/TestRepository.cs ================================================ using MongoDB.Driver; using MongoDbGenericRepository; using MongoDbGenericRepository.Models; using System; using System.Linq.Expressions; using System.Threading.Tasks; namespace IntegrationTests.Infrastructure { public class TestRepository : BaseMongoRepository, ITestRepository { /// public TestRepository(string connectionString, string databaseName) : base(connectionString, databaseName) { } public void DropTestCollection() { MongoDbContext.DropCollection(); } public void DropTestCollection(string partitionKey) { MongoDbContext.DropCollection(partitionKey); } } } ================================================ FILE: IntegrationTests/IntegrationTests.csproj ================================================  Debug AnyCPU {A484A355-A015-40CC-9B35-A4E872421128} Library Properties IntegrationTests IntegrationTests v4.8 512 true full false bin\Debug\ DEBUG;TRACE prompt 4 pdbonly true bin\Release\ TRACE prompt 4 ..\packages\AWSSDK.Core.3.7.100.14\lib\net45\AWSSDK.Core.dll ..\packages\AWSSDK.SecurityToken.3.7.100.14\lib\net45\AWSSDK.SecurityToken.dll ..\packages\DnsClient.1.6.1\lib\net471\DnsClient.dll ..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll ..\packages\Microsoft.Extensions.Logging.Abstractions.2.0.0\lib\netstandard2.0\Microsoft.Extensions.Logging.Abstractions.dll ..\packages\Microsoft.Win32.Registry.5.0.0\lib\net461\Microsoft.Win32.Registry.dll ..\packages\MongoDB.Bson.2.30.0\lib\net472\MongoDB.Bson.dll ..\packages\MongoDB.Driver.2.30.0\lib\net472\MongoDB.Driver.dll ..\packages\MongoDB.Driver.Core.2.30.0\lib\net472\MongoDB.Driver.Core.dll ..\packages\MongoDB.Libmongocrypt.1.12.0\lib\net472\MongoDB.Libmongocrypt.dll ..\packages\NUnit.4.2.2\lib\net462\nunit.framework.dll ..\packages\NUnit.4.2.2\lib\net462\nunit.framework.legacy.dll ..\packages\SharpCompress.0.30.1\lib\net461\SharpCompress.dll ..\packages\Snappier.1.0.0\lib\netstandard2.0\Snappier.dll ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll True True ..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll True True ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll True True ..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll True True ..\packages\System.Security.AccessControl.5.0.0\lib\net461\System.Security.AccessControl.dll ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll True True ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll True True ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll True True ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll True True ..\packages\System.Security.Principal.Windows.5.0.0\lib\net461\System.Security.Principal.Windows.dll ..\packages\System.Text.Encoding.CodePages.5.0.0\lib\net461\System.Text.Encoding.CodePages.dll ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll ..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll ..\packages\ZstdSharp.Port.0.7.3\lib\net461\ZstdSharp.dll Designer {efc776c4-2af3-440c-be80-3fbe335817a5} MongoDbGenericRepository This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. ================================================ FILE: IntegrationTests/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("IntegrationTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IntegrationTests")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("a484a355-a015-40cc-9b35-a4e872421128")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: IntegrationTests/packages.config ================================================  ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 Alexandre SPIESER Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: MongoDbGenericRepository/Abstractions/IBaseMongoRepository.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The IBaseMongoRepository interface exposes the CRUD functionality of the BaseMongoRepository. /// public interface IBaseMongoRepository : IReadOnlyMongoRepository, IBaseMongoRepository_Create, IBaseMongoRepository_Update, IBaseMongoRepository_Delete, IBaseMongoRepository_Index { /// /// Asynchronously returns a paginated list of the documents matching the filter condition. /// /// The type representing a Document. /// /// The number of documents you want to skip. Default value is 0. /// The number of documents you want to take. Default value is 50. /// An optional partition key. /// An optional cancellation token. Task> GetPaginatedAsync( Expression> filter, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument; /// /// Asynchronously returns a paginated list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// /// The number of documents you want to skip. Default value is 0. /// The number of documents you want to take. Default value is 50. /// An optional partition key. /// An optional cancellation token. Task> GetPaginatedAsync( Expression> filter, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// GetAndUpdateOne with filter /// /// The type representing a Document. /// /// /// /// Task GetAndUpdateOne( FilterDefinition filter, UpdateDefinition update, FindOneAndUpdateOptions options) where TDocument : IDocument; /// /// GetAndUpdateOne with filter /// /// The type representing a Document. /// /// /// /// The cancellation token. /// Task GetAndUpdateOne( FilterDefinition filter, UpdateDefinition update, FindOneAndUpdateOptions options, CancellationToken cancellationToken) where TDocument : IDocument; /// /// GetAndUpdateOne with filter /// /// The type representing a Document. /// The type of the primary key for a Document. /// /// /// /// Task GetAndUpdateOne( FilterDefinition filter, UpdateDefinition update, FindOneAndUpdateOptions options) where TDocument : IDocument where TKey : IEquatable; /// /// GetAndUpdateOne with filter /// /// The type representing a Document. /// The type of the primary key for a Document. /// /// /// /// The cancellation token. /// Task GetAndUpdateOne( FilterDefinition filter, UpdateDefinition update, FindOneAndUpdateOptions options, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/Abstractions/IBaseMongoRepository_Update.cs ================================================ using MongoDB.Driver; using MongoDbGenericRepository.Models; using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; namespace MongoDbGenericRepository { /// /// The IBaseMongoRepository_Update interface exposing update functionality for documents with Guid Ids. /// public interface IBaseMongoRepository_Update : IBaseMongoRepository_Update { /// /// Asynchronously Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document with the modifications you want to persist. Task UpdateOneAsync(TDocument modifiedDocument) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document with the modifications you want to persist. /// The cancellation token. Task UpdateOneAsync(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document with the modifications you want to persist. bool UpdateOne(TDocument modifiedDocument) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document with the modifications you want to persist. /// The cancellation token. bool UpdateOne(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to modify. /// The update definition for the document. Task UpdateOneAsync(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument where TKey : IEquatable; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to modify. /// The update definition for the document. /// The cancellation token. Task UpdateOneAsync(TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to modify. /// The update definition for the document. bool UpdateOne(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument where TKey : IEquatable; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to modify. /// The update definition for the document. /// The cancellation token. bool UpdateOne(TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value.. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. bool UpdateOne(Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value.. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. bool UpdateOne(Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value.. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. bool UpdateOne(Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value.. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The cancellation token. bool UpdateOne(Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. Task UpdateOneAsync(TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateOneAsync(TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. Task UpdateOneAsync(Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateOneAsync(Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. Task UpdateOneAsync(Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The cancellation token. Task UpdateOneAsync(Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. bool UpdateOne(TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. /// The cancellation token. bool UpdateOne(TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. Task UpdateOneAsync(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateOneAsync(FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. Task UpdateOneAsync(FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The cancellation token. Task UpdateOneAsync(FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. bool UpdateOne(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. bool UpdateOne(FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. bool UpdateOne(FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The cancellation token. bool UpdateOne(FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. Task UpdateManyAsync(Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateManyAsync(Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. Task UpdateManyAsync(Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The cancellation token. Task UpdateManyAsync(Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. Task UpdateManyAsync(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateManyAsync(FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. Task UpdateManyAsync(FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The cancellation token. Task UpdateManyAsync(FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The cancellation token. Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. /// The cancellation token. Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. Task UpdateManyAsync(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The cancellation token. Task UpdateManyAsync(Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. Task UpdateManyAsync(Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. /// The cancellation token. Task UpdateManyAsync(Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. long UpdateMany(Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. long UpdateMany(Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. long UpdateMany(Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The cancellation token. long UpdateMany(Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. long UpdateMany(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. long UpdateMany(FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. long UpdateMany(FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The cancellation token. long UpdateMany(FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. long UpdateMany(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The cancellation token. long UpdateMany(Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. long UpdateMany(Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. /// The cancellation token. long UpdateMany(Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The cancellation token. long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. /// The cancellation token. long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/Abstractions/IBaseMongoRepository_Update_ClientSession.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Update { /// /// The IBaseMongoRepository_Update_ClientSession interface exposing update functionality with a IClientSessionHandle. /// public interface IBaseMongoRepository_Update_ClientSession { /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional cancellation token. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// The optional cancellation token. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional cancellation token. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// The optional cancellation token. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The document to modify. /// The field to update. /// The value of the field. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The document to modify. /// The field to update. /// The value of the field. /// The optional cancellation token. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document with the modifications you want to persist. /// A boolean value indicating success. bool UpdateOne(IClientSessionHandle session, TDocument modifiedDocument) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document with the modifications you want to persist. /// The optional cancellation token. /// A boolean value indicating success. bool UpdateOne(IClientSessionHandle session, TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document to modify. /// The update definition. /// A boolean value indicating success. bool UpdateOne(IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document to modify. /// The update definition. /// The optional cancellation token. /// A boolean value indicating success. bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// A boolean value indicating success. Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional cancellation token. /// A boolean value indicating success. Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// A boolean value indicating success. Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// The optional cancellation token. /// A boolean value indicating success. Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional cancellation token. /// Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// The optional cancellation token. /// Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The document to modify. /// The field to update. /// The value of the field. /// A boolean value indicating success. Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The document to modify. /// The field to update. /// The value of the field. /// The optional cancellation token. /// A boolean value indicating success. Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document with the modifications you want to persist. /// A boolean value indicating success. Task UpdateOneAsync(IClientSessionHandle session, TDocument modifiedDocument) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document with the modifications you want to persist. /// The optional cancellation token. /// A boolean value indicating success. Task UpdateOneAsync(IClientSessionHandle session, TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document to modify. /// The update definition. /// A boolean value indicating success. Task UpdateOneAsync(IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document to modify. /// The update definition. /// The optional cancellation token. /// A boolean value indicating success. Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/Abstractions/IBaseReadOnlyRepository.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The IBaseReadOnlyRepository exposes the generic Read Only functionality of the BaseMongoRepository. /// public interface IBaseReadOnlyRepository { /// /// The connection string. /// string ConnectionString { get; } /// /// The database name. /// string DatabaseName { get; } #region Read TKey /// /// Asynchronously returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. Task GetByIdAsync(TKey id) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. /// An optional cancellation Token. Task GetByIdAsync(TKey id, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. /// An optional partition key. Task GetByIdAsync(TKey id, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. /// An optional partition key. /// An optional cancellation Token. Task GetByIdAsync(TKey id, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. TDocument GetById(TKey id) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. /// An optional cancellation token. TDocument GetById(TKey id, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. /// An optional partition key. TDocument GetById(TKey id, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. /// An optional partition key. /// An optional cancellation token. TDocument GetById(TKey id, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. Task GetOneAsync(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. Task GetOneAsync(FilterDefinition condition, FindOptions findOption) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. Task GetOneAsync(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. Task GetOneAsync(FilterDefinition condition, FindOptions findOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional cancellation Token. Task GetOneAsync(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional cancellation Token. Task GetOneAsync(FilterDefinition condition, FindOptions findOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. /// An optional cancellation Token. Task GetOneAsync(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. /// An optional cancellation Token. Task GetOneAsync( FilterDefinition condition, FindOptions findOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. TDocument GetOne(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. TDocument GetOne(FilterDefinition condition, FindOptions findOption) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. TDocument GetOne(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. TDocument GetOne(FilterDefinition condition, FindOptions findOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional cancellation token. TDocument GetOne(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional cancellation token. TDocument GetOne(FilterDefinition condition, FindOptions findOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. /// An optional cancellation token. TDocument GetOne(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. /// An optional cancellation token. TDocument GetOne( FilterDefinition condition, FindOptions findOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. Task GetOneAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional cancellation Token. Task GetOneAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. Task GetOneAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation Token. Task GetOneAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. TDocument GetOne(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional cancellation token. TDocument GetOne(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. TDocument GetOne(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation token. TDocument GetOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a collection cursor. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. IFindFluent GetCursor(Expression> filter, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional cancellation Token. Task AnyAsync(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. Task AnyAsync(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. Task AnyAsync(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. Task AnyAsync(FilterDefinition condition, CountOptions countOption) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partition key. Task AnyAsync(FilterDefinition condition, CountOptions countOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. /// An optional cancellation Token. Task AnyAsync(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional cancellation Token. Task AnyAsync(FilterDefinition condition, CountOptions countOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partition key. /// An optional cancellation Token. Task AnyAsync( FilterDefinition condition, CountOptions countOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. bool Any(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. bool Any(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. bool Any(FilterDefinition condition, CountOptions countOption) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partition key. bool Any(FilterDefinition condition, CountOptions countOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional cancellation token. bool Any(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. /// An optional cancellation token. bool Any(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional cancellation token. bool Any(FilterDefinition condition, CountOptions countOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partition key. /// An optional cancellation token. bool Any(FilterDefinition condition, CountOptions countOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. Task AnyAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional cancellation Token. Task AnyAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. Task AnyAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation Token. Task AnyAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. bool Any(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional cancellation Token. bool Any(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. bool Any(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation Token. bool Any(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. Task> GetAllAsync(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. Task> GetAllAsync(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. Task> GetAllAsync(FilterDefinition condition, FindOptions findOption) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. Task> GetAllAsync(FilterDefinition condition, FindOptions findOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional cancellation Token. Task> GetAllAsync(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. /// An optional cancellation Token. Task> GetAllAsync(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional cancellation Token. Task> GetAllAsync(FilterDefinition condition, FindOptions findOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. /// An optional cancellation Token. Task> GetAllAsync( FilterDefinition condition, FindOptions findOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. List GetAll(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. List GetAll(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. List GetAll(FilterDefinition condition, FindOptions findOption) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. List GetAll(FilterDefinition condition, FindOptions findOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional cancellation Token. List GetAll(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partition key. /// An optional cancellation Token. List GetAll(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional cancellation Token. List GetAll(FilterDefinition condition, FindOptions findOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. /// An optional cancellation Token. List GetAll( FilterDefinition condition, FindOptions findOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. Task> GetAllAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional cancellation Token. Task> GetAllAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. Task> GetAllAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation Token. Task> GetAllAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. List GetAll(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional cancellation token. List GetAll(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. List GetAll(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation token. List GetAll(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. Task CountAsync(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partitionKey Task CountAsync(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. Task CountAsync(FilterDefinition condition, CountOptions countOption) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partitionKey Task CountAsync(FilterDefinition condition, CountOptions countOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional cancellation Token. Task CountAsync(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partitionKey /// An optional cancellation Token. Task CountAsync(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional cancellation Token. Task CountAsync(FilterDefinition condition, CountOptions countOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partitionKey /// An optional cancellation Token. Task CountAsync( FilterDefinition condition, CountOptions countOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. long Count(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partitionKey long Count(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. long Count(FilterDefinition condition, CountOptions countOption) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partitionKey long Count(FilterDefinition condition, CountOptions countOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional cancellation token. long Count(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// An optional partitionKey /// An optional cancellation token. long Count(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional cancellation token. long Count(FilterDefinition condition, CountOptions countOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partitionKey /// An optional cancellation token. long Count(FilterDefinition condition, CountOptions countOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. Task CountAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional cancellation Token. Task CountAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partitionKey Task CountAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partitionKey /// An optional cancellation Token. Task CountAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. long Count(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional Cancellation Token. long Count(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partitionKey long Count(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partitionKey /// An optional Cancellation Token. long Count(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; #endregion #region Min / Max /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. Task GetByMaxAsync(Expression> filter, Expression> maxValueSelector) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional cancellation Token. Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. /// An optional cancellation Token. Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. TDocument GetByMax(Expression> filter, Expression> orderByDescending) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional cancellation token. TDocument GetByMax( Expression> filter, Expression> orderByDescending, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. TDocument GetByMax( Expression> filter, Expression> orderByDescending, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. /// An optional cancellation token. TDocument GetByMax( Expression> filter, Expression> orderByDescending, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector for the minimum value you are looking for. Task GetByMinAsync(Expression> filter, Expression> minValueSelector) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector for the minimum value you are looking for. /// An optional cancellation Token. Task GetByMinAsync( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector for the minimum value you are looking for. /// An optional partitionKey. Task GetByMinAsync( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector for the minimum value you are looking for. /// An optional partitionKey. /// An optional cancellation token. Task GetByMinAsync( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector for the minimum value you are looking for. TDocument GetByMin(Expression> filter, Expression> minValueSelector) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector for the minimum value you are looking for. /// An optional cancellation token. TDocument GetByMin( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector for the minimum value you are looking for. /// An optional partitionKey. TDocument GetByMin(Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector for the minimum value you are looking for. /// An optional partitionKey. /// An optional cancellation token. TDocument GetByMin( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector for the maximum value you are looking for. Task GetMaxValueAsync(Expression> filter, Expression> maxValueSelector) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector for the maximum value you are looking for. /// An optional cancellation Token. Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector for the maximum value you are looking for. /// An optional partitionKey. Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector for the maximum value you are looking for. /// An optional partitionKey. /// An optional cancellation token. Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. TValue GetMaxValue(Expression> filter, Expression> maxValueSelector) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional cancellation token. TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. /// An optional cancellation token. TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. Task GetMinValueAsync(Expression> filter, Expression> minValueSelector) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional cancellation Token. Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. /// An optional cancellation token. Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. TValue GetMinValue(Expression> filter, Expression> minValueSelector) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional cancellation token. TValue GetMinValue( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. /// An optional cancellation token. TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; #endregion #region Sum /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. Task SumByAsync(Expression> filter, Expression> selector) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. /// An optional cancellation Token. Task SumByAsync( Expression> filter, Expression> selector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. Task SumByAsync(Expression> filter, Expression> selector, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. /// An optional cancellation token. Task SumByAsync( Expression> filter, Expression> selector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. int SumBy(Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. Task SumByAsync(Expression> filter, Expression> selector) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. /// An optional cancellation token. Task SumByAsync( Expression> filter, Expression> selector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. Task SumByAsync(Expression> filter, Expression> selector, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. /// An optional cancellation token. Task SumByAsync( Expression> filter, Expression> selector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. decimal SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable; #endregion Sum #region Project TKey /// /// Asynchronously returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. Task ProjectOneAsync( Expression> filter, Expression> projection) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional cancellation Token. Task ProjectOneAsync( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. /// An optional cancellation token. Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// /// The projection expression. TProjection ProjectOne(Expression> filter, Expression> projection) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// /// The projection expression. /// An optional cancellation token. TProjection ProjectOne( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// /// The projection expression. /// An optional partition key. TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// /// The projection expression. /// An optional partition key. /// An optional cancellation token. TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. Task> ProjectManyAsync( Expression> filter, Expression> projection) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional cancellation Token. Task> ProjectManyAsync( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. /// An optional cancellation token. Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// /// The projection expression. List ProjectMany( Expression> filter, Expression> projection) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// /// The projection expression. /// An optional cancellation token. List ProjectMany( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// /// The projection expression. /// An optional partition key. List ProjectMany( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// /// The projection expression. /// An optional partition key. /// An optional cancellation token. List ProjectMany( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class; #endregion #region Group By /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The type of the primary key. /// The grouping criteria. /// The projected group result. List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The type of the primary key. /// The grouping criteria. /// The projected group result. /// An optional cancellation token. List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The type of the primary key. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The type of the primary key. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. /// An optional cancellation token. List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The type of the primary key. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The type of the primary key. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. /// An optional cancellation token. List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The type of the primary key. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The type of the primary key. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. /// An optional cancellation token. List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); #endregion Group By #region Pagination /// /// Asynchronously returns a paginated list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The property selector. /// Order of the sorting. /// The number of documents you want to skip. Default value is 0. /// The number of documents you want to take. Default value is 50. /// An optional partition key. /// An optional cancellation token. Task> GetSortedPaginatedAsync( Expression> filter, Expression> sortSelector, bool ascending = true, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a paginated list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The sort definition. /// The number of documents you want to skip. Default value is 0. /// The number of documents you want to take. Default value is 50. /// An optional partition key. /// An optional cancellation Token. Task> GetSortedPaginatedAsync( Expression> filter, SortDefinition sortDefinition, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; #endregion Pagination } } ================================================ FILE: MongoDbGenericRepository/Abstractions/IMongoDbContext.cs ================================================ using MongoDB.Driver; namespace MongoDbGenericRepository { /// /// This is the interface of the IMongoDbContext which is managed by the . /// public interface IMongoDbContext { /// /// The IMongoClient from the official MongoDb driver /// IMongoClient Client { get; } /// /// The IMongoDatabase from the official Mongodb driver /// IMongoDatabase Database { get; } /// /// Returns a collection for a document type that has a partition key. /// /// /// The value of the partition key. IMongoCollection GetCollection(string partitionKey = null); /// /// Drops a collection having a partitionKey, use very carefully. /// /// void DropCollection(string partitionKey = null); /// /// Sets the Guid representation of the MongoDb Driver. /// /// The new value of the GuidRepresentation void SetGuidRepresentation(MongoDB.Bson.GuidRepresentation guidRepresentation); } } ================================================ FILE: MongoDbGenericRepository/Abstractions/IReadOnlyMongoRepository.TKey.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// read only repository interface /// /// The key type public interface IReadOnlyMongoRepository where TKey : IEquatable { #region Read /// /// Asynchronously returns one document given its id. /// /// The type representing a Document. /// The Id of the document you want to get. Task GetByIdAsync(TKey id) where TDocument : IDocument; /// /// Asynchronously returns one document given its id. /// /// The type representing a Document. /// The Id of the document you want to get. /// The cancellation token. Task GetByIdAsync(TKey id, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously returns one document given its id. /// /// The type representing a Document. /// The Id of the document you want to get. /// An optional partition key. Task GetByIdAsync(TKey id, string partitionKey) where TDocument : IDocument; /// /// Asynchronously returns one document given its id. /// /// The type representing a Document. /// The Id of the document you want to get. /// An optional partition key. /// The cancellation token. Task GetByIdAsync(TKey id, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns one document given its id. /// /// The type representing a Document. /// The Id of the document you want to get. TDocument GetById(TKey id) where TDocument : IDocument; /// /// Returns one document given its id. /// /// The type representing a Document. /// The Id of the document you want to get. /// The cancellation token. TDocument GetById(TKey id, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns one document given its id. /// /// The type representing a Document. /// The Id of the document you want to get. /// An optional partition key. TDocument GetById(TKey id, string partitionKey) where TDocument : IDocument; /// /// Returns one document given its id. /// /// The type representing a Document. /// The Id of the document you want to get. /// An optional partition key. /// The cancellation token. TDocument GetById(TKey id, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously returns one document given an expression filter. /// /// The type representing a Document. /// A LINQ expression filter. Task GetOneAsync(Expression> filter) where TDocument : IDocument; /// /// Asynchronously returns one document given an expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token Task GetOneAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously returns one document given an expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. Task GetOneAsync(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Asynchronously returns one document given an expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token Task GetOneAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns one document given an expression filter. /// /// The type representing a Document. /// A LINQ expression filter. TDocument GetOne(Expression> filter) where TDocument : IDocument; /// /// Returns one document given an expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token TDocument GetOne(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns one document given an expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. TDocument GetOne(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Returns one document given an expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token TDocument GetOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns a collection cursor. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. IFindFluent GetCursor(Expression> filter, string partitionKey = null) where TDocument : IDocument; /// /// Asynchronously returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. Task AnyAsync(Expression> filter) where TDocument : IDocument; /// /// Asynchronously returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token. Task AnyAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. Task AnyAsync(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Asynchronously returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. Task AnyAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. bool Any(Expression> filter) where TDocument : IDocument; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token bool Any(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. bool Any(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token bool Any(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. Task> GetAllAsync(Expression> filter) where TDocument : IDocument; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token Task> GetAllAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. Task> GetAllAsync(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token Task> GetAllAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. List GetAll(Expression> filter) where TDocument : IDocument; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token. List GetAll(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. List GetAll(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. List GetAll(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. Task CountAsync(Expression> filter) where TDocument : IDocument; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token. Task CountAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. Task CountAsync(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. Task CountAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. long Count(Expression> filter) where TDocument : IDocument; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// The Cancellation token. long Count(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. long Count(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The Cancellation token. long Count(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; #endregion #region Min / Max /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by descending. Task GetByMaxAsync(Expression> filter, Expression> orderByDescending) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by descending. /// The cancellation token. Task GetByMaxAsync( Expression> filter, Expression> orderByDescending, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. Task GetByMaxAsync( Expression> filter, Expression> orderByDescending, string partitionKey) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. /// The cancellation token. Task GetByMaxAsync( Expression> filter, Expression> orderByDescending, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by descending. /// TDocument GetByMax(Expression> filter, Expression> orderByDescending) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by descending. /// The cancellation token. /// TDocument GetByMax( Expression> filter, Expression> orderByDescending, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. /// TDocument GetByMax(Expression> filter, Expression> orderByDescending, string partitionKey) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. /// The cancellation token. /// TDocument GetByMax( Expression> filter, Expression> orderByDescending, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by ascending. Task GetByMinAsync(Expression> filter, Expression> orderByAscending) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by ascending. /// The cancellation token. Task GetByMinAsync( Expression> filter, Expression> orderByAscending, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. Task GetByMinAsync( Expression> filter, Expression> orderByAscending, string partitionKey) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. /// The cancellation token. Task GetByMinAsync( Expression> filter, Expression> orderByAscending, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by ascending. TDocument GetByMin(Expression> filter, Expression> orderByAscending) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by ascending. /// The cancellation token. TDocument GetByMin( Expression> filter, Expression> orderByAscending, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. TDocument GetByMin(Expression> filter, Expression> orderByAscending, string partitionKey) where TDocument : IDocument; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. /// The cancellation token. TDocument GetByMin( Expression> filter, Expression> orderByAscending, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. Task GetMaxValueAsync(Expression> filter, Expression> maxValueSelector) where TDocument : IDocument; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// The cancellation token. Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. /// The cancellation token. Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. TValue GetMaxValue(Expression> filter, Expression> maxValueSelector) where TDocument : IDocument; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// The cancellation token. TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. /// The cancellation token. TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. Task GetMinValueAsync(Expression> filter, Expression> minValueSelector) where TDocument : IDocument; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// The cancellation token. Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. /// The cancellation token. Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. TValue GetMinValue(Expression> filter, Expression> minValueSelector) where TDocument : IDocument; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// The cancellation token. TValue GetMinValue( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. /// The cancellation token. TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; #endregion #region Maths /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. Task SumByAsync(Expression> filter, Expression> selector) where TDocument : IDocument; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. /// The cancellation token. Task SumByAsync( Expression> filter, Expression> selector, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. Task SumByAsync(Expression> filter, Expression> selector, string partitionKey) where TDocument : IDocument; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. /// The cancellation token. Task SumByAsync( Expression> filter, Expression> selector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. Task SumByAsync(Expression> filter, Expression> selector) where TDocument : IDocument; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. /// The cancellation token. Task SumByAsync( Expression> filter, Expression> selector, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. Task SumByAsync(Expression> filter, Expression> selector, string partitionKey) where TDocument : IDocument; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. /// The cancellation token. Task SumByAsync( Expression> filter, Expression> selector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. int SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. decimal SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument; #endregion Maths #region Project /// /// Asynchronously returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. Task ProjectOneAsync(Expression> filter, Expression> projection) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// The cancellation token Task ProjectOneAsync( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. /// The cancellation token Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class; /// /// Returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. TProjection ProjectOne(Expression> filter, Expression> projection) where TDocument : IDocument where TProjection : class; /// /// Returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// The cancellation token. TProjection ProjectOne( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class; /// /// Returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TProjection : class; /// /// Returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. /// The cancellation token. TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. Task> ProjectManyAsync( Expression> filter, Expression> projection) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// The cancellation token. Task> ProjectManyAsync( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. /// The cancellation token. Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. List ProjectMany(Expression> filter, Expression> projection) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// The cancellation token List ProjectMany( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. List ProjectMany( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. /// The cancellation token List ProjectMany( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class; #endregion Project #region Group By /// /// Groups a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The grouping criteria. /// The projected group result. List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection) where TDocument : IDocument where TProjection : class, new(); /// /// Groups a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The grouping criteria. /// The projected group result. /// The cancellation token. List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class, new(); /// /// Groups a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey) where TDocument : IDocument where TProjection : class, new(); /// /// Groups a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. /// The cancellation token. List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection) where TDocument : IDocument where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. /// The cancellation token. List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey) where TDocument : IDocument where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the grouping criteria. /// The type of the projected group. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. /// The cancellation token. List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class, new(); #endregion Group By #region Pagination /// /// Asynchronously returns a paginated list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// The property selector. /// Order of the sorting. /// The number of documents you want to skip. Default value is 0. /// The number of documents you want to take. Default value is 50. /// An optional partition key. /// An optional cancellation token. Task> GetSortedPaginatedAsync( Expression> filter, Expression> sortSelector, bool ascending = true, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument; /// /// Asynchronously returns a paginated list of the documents matching the filter condition. /// /// The type representing a Document. /// A LINQ expression filter. /// The sort definition. /// The number of documents you want to skip. Default value is 0. /// The number of documents you want to take. Default value is 50. /// An optional partition key. /// An optional cancellation token. Task> GetSortedPaginatedAsync( Expression> filter, SortDefinition sortDefinition, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument; #endregion Pagination } } ================================================ FILE: MongoDbGenericRepository/Abstractions/IReadOnlyMongoRepository.cs ================================================ using System; namespace MongoDbGenericRepository { /// /// The IReadOnlyMongoRepository exposes the readonly functionality of the BaseMongoRepository. /// public interface IReadOnlyMongoRepository : IBaseReadOnlyRepository, IReadOnlyMongoRepository { } } ================================================ FILE: MongoDbGenericRepository/Attributes/CollectionNameAttribute.cs ================================================ using System; namespace MongoDbGenericRepository.Attributes { /// /// This attribute allows you to specify of the name of the collection. /// Added at commit c117bf2a7fee378f1e02199dea9b2023a7089ee2 by https://github.com/Etchelon /// who has included the CollectionName attribute into the repo to give another choice to the user on how /// to name their collections. /// The attribute takes precedence of course, and if not present the library will fall back to your Pluralize method. /// [AttributeUsage(AttributeTargets.Class)] public class CollectionNameAttribute : Attribute { /// /// The name of the collection in which your documents are stored. /// public string Name { get; set; } /// /// The constructor. /// /// The name of the collection. public CollectionNameAttribute(string name) { this.Name = name; } } } ================================================ FILE: MongoDbGenericRepository/BaseMongoRepository.Create.cs ================================================ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Create; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. /// Its constructor must be given a connection string and a database name. /// public abstract partial class BaseMongoRepository : IBaseMongoRepository_Create { private readonly object _initLock = new object(); private IMongoDbCreator _mongoDbCreator; /// /// The MongoDbCreator field. /// protected virtual IMongoDbCreator MongoDbCreator { get { if (_mongoDbCreator != null) { return _mongoDbCreator; } lock (_initLock) { if (_mongoDbCreator == null) { _mongoDbCreator = new MongoDbCreator(MongoDbContext); } } return _mongoDbCreator; } set => _mongoDbCreator = value; } /// public virtual async Task AddOneAsync(TDocument document) where TDocument : IDocument where TKey : IEquatable { await AddOneAsync(document, CancellationToken.None); } /// public virtual async Task AddOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { await MongoDbCreator.AddOneAsync(document, cancellationToken); } /// public virtual async Task AddOneAsync(TDocument document) where TDocument : IDocument { await AddOneAsync(document, CancellationToken.None); } /// public virtual async Task AddOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument { await AddOneAsync(document, cancellationToken); } /// public virtual void AddOne(TDocument document) where TDocument : IDocument where TKey : IEquatable { AddOne(document, CancellationToken.None); } /// public virtual void AddOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { MongoDbCreator.AddOne(document, cancellationToken); } /// public virtual void AddOne(TDocument document) where TDocument : IDocument { AddOne(document, CancellationToken.None); } /// public virtual void AddOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument { AddOne(document, cancellationToken); } /// public virtual async Task AddManyAsync(IEnumerable documents) where TDocument : IDocument where TKey : IEquatable { await AddManyAsync(documents, CancellationToken.None); } /// public virtual async Task AddManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { await MongoDbCreator.AddManyAsync(documents, cancellationToken); } /// public virtual async Task AddManyAsync(IEnumerable documents) where TDocument : IDocument { await AddManyAsync(documents, CancellationToken.None); } /// public virtual async Task AddManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument { await AddManyAsync(documents, cancellationToken); } /// public virtual void AddMany(IEnumerable documents) where TDocument : IDocument where TKey : IEquatable { AddMany(documents, CancellationToken.None); } /// public virtual void AddMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { MongoDbCreator.AddMany(documents, cancellationToken); } /// public virtual void AddMany(IEnumerable documents) where TDocument : IDocument { AddMany(documents, CancellationToken.None); } /// public virtual void AddMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument { AddMany(documents, cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/BaseMongoRepository.Delete.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Delete; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { public abstract partial class BaseMongoRepository : IBaseMongoRepository_Delete { private IMongoDbEraser _mongoDbEraser; /// /// The MongoDbEraser used to delete documents. /// protected virtual IMongoDbEraser MongoDbEraser { get { if (_mongoDbEraser != null) { return _mongoDbEraser; } lock (_initLock) { if (_mongoDbEraser == null) { _mongoDbEraser = new MongoDbEraser(MongoDbContext); } } return _mongoDbEraser; } set => _mongoDbEraser = value; } #region Delete /// public virtual long DeleteOne(TDocument document) where TDocument : IDocument { return DeleteOne(document, CancellationToken.None); } /// public virtual long DeleteOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument { return DeleteOne(document, cancellationToken); } /// public virtual long DeleteOne(Expression> filter) where TDocument : IDocument { return DeleteOne(filter, null, CancellationToken.None); } /// public virtual long DeleteOne(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return DeleteOne(filter, null, cancellationToken); } /// public virtual long DeleteOne(Expression> filter, string partitionKey) where TDocument : IDocument { return DeleteOne(filter, partitionKey, CancellationToken.None); } /// public virtual long DeleteOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return DeleteOne(filter, partitionKey, cancellationToken); } /// public virtual async Task DeleteOneAsync(TDocument document) where TDocument : IDocument { return await DeleteOneAsync(document, CancellationToken.None); } /// public virtual async Task DeleteOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument { return await DeleteOneAsync(document, cancellationToken); } /// public virtual async Task DeleteOneAsync(Expression> filter) where TDocument : IDocument { return await DeleteOneAsync(filter, null, CancellationToken.None); } /// public virtual async Task DeleteOneAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return await DeleteOneAsync(filter, null, cancellationToken); } /// public virtual async Task DeleteOneAsync(Expression> filter, string partitionKey) where TDocument : IDocument { return await DeleteOneAsync(filter, partitionKey, CancellationToken.None); } /// public virtual async Task DeleteOneAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await DeleteOneAsync(filter, partitionKey, cancellationToken); } /// public async Task DeleteManyAsync(Expression> filter) where TDocument : IDocument { return await DeleteManyAsync(filter, null, CancellationToken.None); } /// public async Task DeleteManyAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return await DeleteManyAsync(filter, null, cancellationToken); } /// public virtual async Task DeleteManyAsync(Expression> filter, string partitionKey) where TDocument : IDocument { return await DeleteManyAsync(filter, partitionKey, CancellationToken.None); } /// public async Task DeleteManyAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await DeleteManyAsync(filter, partitionKey, cancellationToken); } /// public virtual async Task DeleteManyAsync(IEnumerable documents) where TDocument : IDocument { return await DeleteManyAsync(documents); } /// public virtual async Task DeleteManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument { return await DeleteManyAsync(documents, cancellationToken); } /// public virtual long DeleteMany(IEnumerable documents) where TDocument : IDocument { return DeleteMany(documents, CancellationToken.None); } /// public virtual long DeleteMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument { return DeleteMany(documents, cancellationToken); } /// public virtual long DeleteMany(Expression> filter) where TDocument : IDocument { return DeleteMany(filter, null, CancellationToken.None); } /// public virtual long DeleteMany(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return DeleteMany(filter, null, cancellationToken); } /// public virtual long DeleteMany(Expression> filter, string partitionKey) where TDocument : IDocument { return DeleteMany(filter, partitionKey, CancellationToken.None); } /// public virtual long DeleteMany(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return DeleteMany(filter, partitionKey, cancellationToken); } #endregion Delete #region Delete TKey /// public virtual long DeleteOne(TDocument document) where TDocument : IDocument where TKey : IEquatable { return DeleteOne(document, CancellationToken.None); } /// public virtual long DeleteOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbEraser.DeleteOne(document, cancellationToken); } /// public virtual long DeleteOne(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return DeleteOne(filter, null, CancellationToken.None); } /// public virtual long DeleteOne(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return DeleteOne(filter, null, cancellationToken); } /// public virtual long DeleteOne(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return DeleteOne(filter, partitionKey, CancellationToken.None); } /// public virtual long DeleteOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbEraser.DeleteOne(filter, partitionKey, cancellationToken); } /// public virtual async Task DeleteOneAsync(TDocument document) where TDocument : IDocument where TKey : IEquatable { return await DeleteOneAsync(document, CancellationToken.None); } /// public virtual async Task DeleteOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbEraser.DeleteOneAsync(document, cancellationToken); } /// public virtual async Task DeleteOneAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return await DeleteOneAsync(filter, null, CancellationToken.None); } /// public virtual async Task DeleteOneAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await DeleteOneAsync(filter, null, cancellationToken); } /// public virtual async Task DeleteOneAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await DeleteOneAsync(filter, partitionKey, CancellationToken.None); } /// public virtual async Task DeleteOneAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbEraser.DeleteOneAsync(filter, partitionKey, cancellationToken); } /// public virtual async Task DeleteManyAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return await DeleteManyAsync(filter, null, CancellationToken.None); } /// public virtual async Task DeleteManyAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await DeleteManyAsync(filter, null, cancellationToken); } /// public virtual async Task DeleteManyAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await DeleteManyAsync(filter, partitionKey, CancellationToken.None); } /// public virtual async Task DeleteManyAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbEraser.DeleteManyAsync(filter, partitionKey, cancellationToken); } /// public virtual async Task DeleteManyAsync(IEnumerable documents) where TDocument : IDocument where TKey : IEquatable { return await DeleteManyAsync(documents, CancellationToken.None); } /// public virtual async Task DeleteManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbEraser.DeleteManyAsync(documents, cancellationToken); } /// public virtual long DeleteMany(IEnumerable documents) where TDocument : IDocument where TKey : IEquatable { return DeleteMany(documents, CancellationToken.None); } /// public virtual long DeleteMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbEraser.DeleteMany(documents, cancellationToken); } /// public virtual long DeleteMany(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return DeleteMany(filter, null, CancellationToken.None); } /// public virtual long DeleteMany(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return DeleteMany(filter, null, cancellationToken); } /// public virtual long DeleteMany(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return DeleteMany(filter, partitionKey, CancellationToken.None); } /// public virtual long DeleteMany(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbEraser.DeleteMany(filter, partitionKey, cancellationToken); } #endregion } } ================================================ FILE: MongoDbGenericRepository/BaseMongoRepository.Index.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. /// Its constructor must be given a connection string and a database name. /// public abstract partial class BaseMongoRepository : IBaseMongoRepository_Index { private IMongoDbIndexHandler _mongoDbIndexHandler; /// /// The MongoDb accessor to manage indexes. /// protected virtual IMongoDbIndexHandler MongoDbIndexHandler { get { if (_mongoDbIndexHandler != null) { return _mongoDbIndexHandler; } lock (_initLock) { if (_mongoDbIndexHandler == null) { _mongoDbIndexHandler = new MongoDbIndexHandler(MongoDbContext); } } return _mongoDbIndexHandler; } set => _mongoDbIndexHandler = value; } /// public async Task> GetIndexesNamesAsync() where TDocument : IDocument { return await GetIndexesNamesAsync(null, CancellationToken.None); } /// public async Task> GetIndexesNamesAsync(CancellationToken cancellationToken) where TDocument : IDocument { return await GetIndexesNamesAsync(null, cancellationToken); } /// public async Task> GetIndexesNamesAsync(string partitionKey) where TDocument : IDocument { return await GetIndexesNamesAsync(partitionKey); } /// public async Task> GetIndexesNamesAsync(string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await GetIndexesNamesAsync(partitionKey, cancellationToken); } /// public virtual async Task> GetIndexesNamesAsync() where TDocument : IDocument where TKey : IEquatable { return await GetIndexesNamesAsync(null, CancellationToken.None); } /// public virtual async Task> GetIndexesNamesAsync(CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await GetIndexesNamesAsync(null, cancellationToken); } /// public virtual async Task> GetIndexesNamesAsync(string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await GetIndexesNamesAsync(partitionKey, CancellationToken.None); } /// public virtual async Task> GetIndexesNamesAsync(string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbIndexHandler.GetIndexesNamesAsync(partitionKey, cancellationToken); } /// public async Task CreateTextIndexAsync(Expression> field) where TDocument : IDocument { return await CreateTextIndexAsync(field, null, null, CancellationToken.None); } /// public async Task CreateTextIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateTextIndexAsync(field, null, null, cancellationToken); } /// public async Task CreateTextIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument { return await CreateTextIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public async Task CreateTextIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateTextIndexAsync(field, null, partitionKey, cancellationToken); } /// public async Task CreateTextIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateTextIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateTextIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateTextIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateTextIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task CreateTextIndexAsync(Expression> field) where TDocument : IDocument where TKey : IEquatable { return await CreateTextIndexAsync(field, null, null, CancellationToken.None); } /// public virtual async Task CreateTextIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateTextIndexAsync(field, null, null, cancellationToken); } /// public virtual async Task CreateTextIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateTextIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateTextIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateTextIndexAsync(field, null, partitionKey, cancellationToken); } /// public virtual async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable { return await CreateTextIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateTextIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateTextIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbIndexHandler.CreateTextIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public async Task CreateAscendingIndexAsync(Expression> field) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, null, null, CancellationToken.None); } /// public async Task CreateAscendingIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, null, null, cancellationToken); } /// public async Task CreateAscendingIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public async Task CreateAscendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public async Task CreateAscendingIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, null, partitionKey, cancellationToken); } /// public async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task CreateAscendingIndexAsync(Expression> field) where TDocument : IDocument where TKey : IEquatable { return await CreateAscendingIndexAsync(field, null, null, CancellationToken.None); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateAscendingIndexAsync(field, null, null, cancellationToken); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable { return await CreateAscendingIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateAscendingIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateAscendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateAscendingIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateAscendingIndexAsync(field, null, partitionKey, cancellationToken); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateAscendingIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbIndexHandler.CreateAscendingIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public async Task CreateDescendingIndexAsync(Expression> field) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, null, null, CancellationToken.None); } /// public async Task CreateDescendingIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, null, null, cancellationToken); } /// public async Task CreateDescendingIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public async Task CreateDescendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public async Task CreateDescendingIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, null, partitionKey, cancellationToken); } /// public async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task CreateDescendingIndexAsync(Expression> field) where TDocument : IDocument where TKey : IEquatable { return await CreateDescendingIndexAsync(field, null, null, CancellationToken.None); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateDescendingIndexAsync(field, null, null, cancellationToken); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable { return await CreateDescendingIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateDescendingIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateDescendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateDescendingIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateDescendingIndexAsync(field, null, partitionKey, cancellationToken); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateDescendingIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbIndexHandler.CreateDescendingIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public async Task CreateHashedIndexAsync(Expression> field) where TDocument : IDocument { return await CreateHashedIndexAsync(field, null, null, CancellationToken.None); } /// public async Task CreateHashedIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateHashedIndexAsync(field, null, null, cancellationToken); } /// public async Task CreateHashedIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateHashedIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateHashedIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public async Task CreateHashedIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument { return await CreateHashedIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public async Task CreateHashedIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateHashedIndexAsync(field, null, partitionKey, cancellationToken); } /// public async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateHashedIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateHashedIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task CreateHashedIndexAsync(Expression> field) where TDocument : IDocument where TKey : IEquatable { return await CreateHashedIndexAsync(field, null, null, CancellationToken.None); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateHashedIndexAsync(field, null, null, cancellationToken); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable { return await CreateHashedIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateHashedIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateHashedIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateHashedIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateHashedIndexAsync(field, null, partitionKey, cancellationToken); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateHashedIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbIndexHandler.CreateHashedIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public async Task CreateCombinedTextIndexAsync(IEnumerable>> fields) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, null, null, CancellationToken.None); } /// public async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, null, null, cancellationToken); } /// public async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, null, CancellationToken.None); } /// public async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, null, cancellationToken); } /// public async Task CreateCombinedTextIndexAsync(IEnumerable>> fields, string partitionKey) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, null, partitionKey, CancellationToken.None); } /// public async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, null, partitionKey, cancellationToken); } /// public async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, partitionKey, CancellationToken.None); } /// public async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task CreateCombinedTextIndexAsync(IEnumerable>> fields) where TDocument : IDocument where TKey : IEquatable { return await CreateCombinedTextIndexAsync(fields, null, null, CancellationToken.None); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateCombinedTextIndexAsync(fields, null, null, cancellationToken); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateCombinedTextIndexAsync(fields, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CreateCombinedTextIndexAsync(fields, null, partitionKey, cancellationToken); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbIndexHandler.CreateCombinedTextIndexAsync(fields, indexCreationOptions, partitionKey, cancellationToken); } /// public async Task DropIndexAsync(string indexName) where TDocument : IDocument { await DropIndexAsync(indexName, null, CancellationToken.None); } /// public async Task DropIndexAsync(string indexName, CancellationToken cancellationToken) where TDocument : IDocument { await DropIndexAsync(indexName, null, cancellationToken); } /// public async Task DropIndexAsync(string indexName, string partitionKey) where TDocument : IDocument { await DropIndexAsync(indexName, partitionKey, CancellationToken.None); } /// public async Task DropIndexAsync(string indexName, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { await DropIndexAsync(indexName, partitionKey, cancellationToken); } /// public virtual async Task DropIndexAsync(string indexName) where TDocument : IDocument where TKey : IEquatable { await DropIndexAsync(indexName, null, CancellationToken.None); } /// public virtual async Task DropIndexAsync(string indexName, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { await DropIndexAsync(indexName, null, cancellationToken); } /// public virtual async Task DropIndexAsync(string indexName, string partitionKey) where TDocument : IDocument where TKey : IEquatable { await DropIndexAsync(indexName, partitionKey, CancellationToken.None); } /// public virtual async Task DropIndexAsync(string indexName, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { await MongoDbIndexHandler.DropIndexAsync(indexName, partitionKey, cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/BaseMongoRepository.Main.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; using MongoDbGenericRepository.Utils; namespace MongoDbGenericRepository { /// /// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. /// Its constructor must be given a connection string and a database name. /// public abstract partial class BaseMongoRepository : ReadOnlyMongoRepository, IBaseMongoRepository { /// /// The constructor taking a connection string and a database name. /// /// The connection string of the MongoDb server. /// The name of the database against which you want to perform operations. protected BaseMongoRepository(string connectionString, string databaseName = null) : base(connectionString, databaseName) { } /// /// The constructor taking a . /// /// A mongodb context implementing protected BaseMongoRepository(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } /// /// The constructor taking a . /// /// A mongodb context implementing protected BaseMongoRepository(IMongoDatabase mongoDatabase) : base(mongoDatabase) { } /// public virtual async Task> GetPaginatedAsync( Expression> filter, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument { return await HandlePartitioned(partitionKey).Find(filter).Skip(skipNumber).Limit(takeNumber).ToListAsync(cancellationToken); } /// public virtual async Task> GetPaginatedAsync( Expression> filter, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await HandlePartitioned(partitionKey).Find(filter).Skip(skipNumber).Limit(takeNumber).ToListAsync(cancellationToken); } /// /// Sets the value of the document Id if it is not set already. /// /// The document type. /// The type of the primary key. /// The document. protected void FormatDocument(TDocument document) where TDocument : IDocument where TKey : IEquatable { if (document == null) { throw new ArgumentNullException(nameof(document)); } var defaultTKey = default(TKey); if (document.Id == null || (defaultTKey != null && defaultTKey.Equals(document.Id))) { document.Id = IdGenerator.GetId(); } } /// /// Sets the value of the document Id if it is not set already. /// /// The document type. /// The document. protected void FormatDocument(TDocument document) where TDocument : IDocument { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (document.Id == default) { document.Id = Guid.NewGuid(); } } /// /// Gets a collections for a potentially partitioned document type. /// /// The document type. /// The collection partition key. /// protected virtual IMongoCollection HandlePartitioned(string partitionKey) where TDocument : IDocument { if (!string.IsNullOrEmpty(partitionKey)) { return GetCollection(partitionKey); } return GetCollection(); } /// /// Gets a collections for the type TDocument with a partition key. /// /// The document type. /// The collection partition key. /// protected virtual IMongoCollection GetCollection(string partitionKey = null) where TDocument : IDocument { return MongoDbContext.GetCollection(partitionKey); } #region Find And Update /// public virtual async Task GetAndUpdateOne( FilterDefinition filter, UpdateDefinition update, FindOneAndUpdateOptions options) where TDocument : IDocument { return await GetAndUpdateOne(filter, update, options, CancellationToken.None); } /// public virtual async Task GetAndUpdateOne( FilterDefinition filter, UpdateDefinition update, FindOneAndUpdateOptions options, CancellationToken cancellationToken) where TDocument : IDocument { return await GetCollection().FindOneAndUpdateAsync(filter, update, options, cancellationToken); } /// public virtual async Task GetAndUpdateOne( FilterDefinition filter, UpdateDefinition update, FindOneAndUpdateOptions options) where TDocument : IDocument where TKey : IEquatable { return await GetAndUpdateOne(filter, update, options, CancellationToken.None); } /// public virtual async Task GetAndUpdateOne( FilterDefinition filter, UpdateDefinition update, FindOneAndUpdateOptions options, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await GetCollection().FindOneAndUpdateAsync(filter, update, options, cancellationToken); } #endregion Find And Update } } ================================================ FILE: MongoDbGenericRepository/BaseMongoRepository.Update.ClientSession.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { public abstract partial class BaseMongoRepository : IBaseMongoRepository_Update_ClientSession { /// public virtual async Task UpdateOneAsync(IClientSessionHandle session, TDocument modifiedDocument) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(session, modifiedDocument, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync(session, modifiedDocument, cancellationToken); } /// public virtual bool UpdateOne(IClientSessionHandle session, TDocument modifiedDocument) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, modifiedDocument, CancellationToken.None); } /// public virtual bool UpdateOne(IClientSessionHandle session, TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateOne(session, modifiedDocument, cancellationToken); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(session, documentToModify, update, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync(session, documentToModify, update, cancellationToken); } /// public virtual bool UpdateOne(IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, documentToModify, update, CancellationToken.None); } /// public virtual bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateOne(session, documentToModify, update, cancellationToken); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(session, documentToModify, field, value, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync(session, documentToModify, field, value, cancellationToken); } /// public virtual bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, documentToModify, field, value, CancellationToken.None); } /// public virtual bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateOne(session, documentToModify, field, value, cancellationToken); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(session, filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(session, filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(session, filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync(session, filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(session, filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(session, filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(session, filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync(session, filter, field, value, partitionKey, cancellationToken); } /// public virtual bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, filter, field, value, null, CancellationToken.None); } /// public virtual bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, filter, field, value, null, cancellationToken); } /// public virtual bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, filter, field, value, partitionKey, CancellationToken.None); } /// public virtual bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateOne(session, filter, field, value, partitionKey, cancellationToken); } /// public virtual bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, Builders.Filter.Where(filter), field, value, null, CancellationToken.None); } /// public virtual bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, Builders.Filter.Where(filter), field, value, null, cancellationToken); } /// public virtual bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, Builders.Filter.Where(filter), field, value, partitionKey, CancellationToken.None); } /// public virtual bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, Builders.Filter.Where(filter), field, value, partitionKey, cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/BaseMongoRepository.Update.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. /// Its constructor must be given a connection string and a database name. /// public abstract partial class BaseMongoRepository : IBaseMongoRepository_Update { private IMongoDbUpdater _mongoDbUpdater; /// /// The MongoDb accessor to update data. /// protected virtual IMongoDbUpdater MongoDbUpdater { get { if (_mongoDbUpdater != null) { return _mongoDbUpdater; } lock (_initLock) { if (_mongoDbUpdater == null) { _mongoDbUpdater = new MongoDbUpdater(MongoDbContext); } } return _mongoDbUpdater; } set => _mongoDbUpdater = value; } #region Update /// public virtual async Task UpdateOneAsync(TDocument modifiedDocument) where TDocument : IDocument { return await UpdateOneAsync(modifiedDocument, CancellationToken.None); } /// public virtual async Task UpdateOneAsync(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(modifiedDocument, cancellationToken); } /// public virtual bool UpdateOne(TDocument modifiedDocument) where TDocument : IDocument { return UpdateOne(modifiedDocument, CancellationToken.None); } /// public virtual bool UpdateOne(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(modifiedDocument, cancellationToken); } /// public virtual async Task UpdateOneAsync(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument { return await UpdateOneAsync(documentToModify, update, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(documentToModify, update, cancellationToken); } /// public virtual bool UpdateOne(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument { return UpdateOne(documentToModify, update, CancellationToken.None); } /// public virtual bool UpdateOne(TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(documentToModify, update, cancellationToken); } /// public virtual bool UpdateOne(TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument { return UpdateOne(documentToModify, field, value, CancellationToken.None); } /// public virtual bool UpdateOne( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(documentToModify, field, value, cancellationToken); } /// public virtual async Task UpdateOneAsync(TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument { return await UpdateOneAsync(documentToModify, field, value, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(documentToModify, field, value, cancellationToken); } /// public virtual bool UpdateOne(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument { return UpdateOne(filter, field, value, null, CancellationToken.None); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateOne(filter, field, value, null, cancellationToken); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return UpdateOne(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(filter, field, value, partitionKey, cancellationToken); } /// public virtual bool UpdateOne(Expression> filter, Expression> field, TField value) where TDocument : IDocument { return UpdateOne(filter, field, value, null, CancellationToken.None); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateOne(filter, field, value, null, cancellationToken); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return UpdateOne(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateManyAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateManyAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateManyAsync(filter, updateDefinition, partitionKey, cancellationToken); } /// public async Task UpdateManyAsync(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, null, CancellationToken.None); } /// public async Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, null, cancellationToken); } /// public async Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public async Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateManyAsync(filter, updateDefinition, partitionKey, cancellationToken); } /// public virtual long UpdateMany(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument { return UpdateMany(filter, field, value, null, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateMany(filter, field, value, null, cancellationToken); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return UpdateMany(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, field, value, partitionKey, cancellationToken); } /// public virtual long UpdateMany(Expression> filter, Expression> field, TField value) where TDocument : IDocument { return UpdateMany(filter, field, value, null, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateMany(filter, field, value, null, cancellationToken); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return UpdateMany(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, field, value, partitionKey, cancellationToken); } /// public virtual long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, null, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, null, cancellationToken); } /// public virtual long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, updateDefinition, partitionKey, cancellationToken); } /// public long UpdateMany(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, null, CancellationToken.None); } /// public long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, null, cancellationToken); } /// public long UpdateMany(Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, updateDefinition, partitionKey, cancellationToken); } #endregion Update #region Update TKey /// public virtual async Task UpdateOneAsync(TDocument modifiedDocument) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(modifiedDocument, CancellationToken.None); } /// public virtual async Task UpdateOneAsync(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync(modifiedDocument, cancellationToken); } /// public virtual bool UpdateOne(TDocument modifiedDocument) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(modifiedDocument, CancellationToken.None); } /// public virtual bool UpdateOne(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateOne(modifiedDocument, cancellationToken); } /// public virtual async Task UpdateOneAsync(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(documentToModify, update, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync(documentToModify, update, cancellationToken); } /// public virtual bool UpdateOne(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(documentToModify, update, CancellationToken.None); } /// public virtual bool UpdateOne(TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateOne(documentToModify, update, cancellationToken); } /// public virtual bool UpdateOne(TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(documentToModify, field, value, CancellationToken.None); } /// public virtual bool UpdateOne( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateOne(documentToModify, field, value, cancellationToken); } /// public virtual async Task UpdateOneAsync( TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(documentToModify, field, value, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync(documentToModify, field, value, cancellationToken); } /// public virtual bool UpdateOne(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(filter, field, value, null, CancellationToken.None); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(filter, field, value, null, cancellationToken); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateOne(filter, field, value, partitionKey, cancellationToken); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(filter, field, value, null, CancellationToken.None); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(filter, field, value, null, cancellationToken); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateOne(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(Builders.Filter.Where(filter), field, value, null, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(Builders.Filter.Where(filter), field, value, null, cancellationToken); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(Builders.Filter.Where(filter), field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateOneAsync( Builders.Filter.Where(filter), field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateManyAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateManyAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, updateDefinition, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, updateDefinition, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateManyAsync(filter, updateDefinition, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, updateDefinition, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, updateDefinition, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbUpdater.UpdateManyAsync(filter, updateDefinition, partitionKey, cancellationToken); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, field, value, null, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, field, value, null, cancellationToken); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateMany(filter, field, value, partitionKey, cancellationToken); } /// public virtual long UpdateMany(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, field, value, null, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, field, value, null, cancellationToken); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateMany(filter, field, value, partitionKey, cancellationToken); } /// public virtual long UpdateMany(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, updateDefinition, null, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, updateDefinition, null, cancellationToken); } /// public virtual long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateMany(filter, updateDefinition, partitionKey, cancellationToken); } /// public virtual long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, updateDefinition, null, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, updateDefinition, null, cancellationToken); } /// public virtual long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbUpdater.UpdateMany(filter, updateDefinition, partitionKey, cancellationToken); } #endregion Update } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Base/DataAccessBase.cs ================================================ using MongoDB.Driver; using MongoDB.Driver.Linq; using MongoDbGenericRepository.Models; using System.Linq.Expressions; namespace MongoDbGenericRepository.DataAccess.Base { /// /// A base class for accessing the Database and its Collections. /// public class DataAccessBase : IDataAccessBase { /// /// The MongoDbContext /// protected IMongoDbContext MongoDbContext; /// /// The constructor of the DataAccessBase class /// /// public DataAccessBase(IMongoDbContext mongoDbContext) { MongoDbContext = mongoDbContext; } #region Utility Methods /// /// Gets a IMongoQueryable for a potentially partitioned document type and a filter. /// /// The document type. /// The type of the primary key. /// The filter definition. /// The collection partition key. /// #if NETSTANDARD2_0 || NET472 public virtual IMongoQueryable GetQuery(Expression> filter, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return GetCollection(partitionKey).AsQueryable().Where(filter); } #endif #if NETSTANDARD2_1_OR_GREATER public virtual IQueryable GetQuery(Expression> filter, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return GetCollection(partitionKey).AsQueryable().Where(filter); } #endif /// /// Gets a collections for a potentially partitioned document type. /// /// The document type. /// The type of the primary key. /// The document. /// public virtual IMongoCollection HandlePartitioned(TDocument document) where TDocument : IDocument where TKey : IEquatable { if (document is IPartitionedDocument) { return GetCollection(((IPartitionedDocument)document).PartitionKey); } return GetCollection(); } /// /// Gets a collections for the type TDocument with a partition key. /// /// The document type. /// The type of the primary key. /// The collection partition key. /// public virtual IMongoCollection GetCollection(string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return MongoDbContext.GetCollection(partitionKey); } /// /// Gets a collections for a potentially partitioned document type. /// /// The document type. /// The type of the primary key. /// The collection partition key. /// public virtual IMongoCollection HandlePartitioned(string partitionKey) where TDocument : IDocument where TKey : IEquatable { if (!string.IsNullOrEmpty(partitionKey)) { return GetCollection(partitionKey); } return GetCollection(); } /// /// Converts a LINQ expression of TDocument, TValue to a LINQ expression of TDocument, object /// /// The document type. /// The type of the value. /// The expression to convert protected virtual Expression> ConvertExpression(Expression> expression) { var param = expression.Parameters[0]; Expression body = expression.Body; var convert = Expression.Convert(body, typeof(object)); return Expression.Lambda>(convert, param); } /// /// Maps a IndexCreationOptions object to a MongoDB.Driver.CreateIndexOptions object /// /// The options for creating an index. /// protected virtual CreateIndexOptions MapIndexOptions(IndexCreationOptions indexCreationOptions) { return new CreateIndexOptions { Unique = indexCreationOptions.Unique, TextIndexVersion = indexCreationOptions.TextIndexVersion, SphereIndexVersion = indexCreationOptions.SphereIndexVersion, Sparse = indexCreationOptions.Sparse, Name = indexCreationOptions.Name, Min = indexCreationOptions.Min, Max = indexCreationOptions.Max, LanguageOverride = indexCreationOptions.LanguageOverride, ExpireAfter = indexCreationOptions.ExpireAfter, DefaultLanguage = indexCreationOptions.DefaultLanguage, Bits = indexCreationOptions.Bits, Background = indexCreationOptions.Background, Version = indexCreationOptions.Version }; } /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. protected virtual IFindFluent GetMinMongoQuery(Expression> filter, Expression> minValueSelector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return GetCollection(partitionKey).Find(Builders.Filter.Where(filter)) .SortBy(ConvertExpression(minValueSelector)) .Limit(1); } /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partition key. protected virtual IFindFluent GetMaxMongoQuery(Expression> filter, Expression> maxValueSelector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return GetCollection(partitionKey).Find(Builders.Filter.Where(filter)) .SortByDescending(ConvertExpression(maxValueSelector)) .Limit(1); } #endregion } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Base/IDataAccessBase.cs ================================================ using MongoDB.Driver; using MongoDB.Driver.Linq; using MongoDbGenericRepository.Models; using System.Linq.Expressions; namespace MongoDbGenericRepository.DataAccess.Base { /// /// A interface for accessing the Database and its Collections. /// public interface IDataAccessBase { /// /// Gets a IMongoQueryable for a potentially partitioned document type and a filter. /// /// The document type. /// The type of the primary key. /// The filter definition. /// The collection partition key. /// #if NETSTANDARD2_0 || NET472 IMongoQueryable GetQuery(Expression> filter, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable; #elif NETSTANDARD2_1_OR_GREATER IQueryable GetQuery(Expression> filter, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable; #endif /// /// Gets a collections for a potentially partitioned document type. /// /// The document type. /// The type of the primary key. /// The document. /// IMongoCollection HandlePartitioned(TDocument document) where TDocument : IDocument where TKey : IEquatable; /// /// Gets a collections for a potentially partitioned document type. /// /// The document type. /// The type of the primary key. /// The collection partition key. /// IMongoCollection HandlePartitioned(string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Gets a collections for the type TDocument with a partition key. /// /// The document type. /// The type of the primary key. /// The collection partition key. /// IMongoCollection GetCollection(string partitionKey = null) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Create/IMongoDbCreator.cs ================================================ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Create { /// /// A interface for adding documents to the Database and its Collections. /// public interface IMongoDbCreator : IDataAccessBase { /// /// Asynchronously adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to add. /// An optional cancellation Token. Task AddOneAsync(TDocument document, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to add. /// An optional cancellation Token. void AddOne(TDocument document, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The documents you want to add. /// An optional cancellation Token. Task AddManyAsync(IEnumerable documents, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The documents you want to add. /// An optional cancellation Token. void AddMany(IEnumerable documents, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Create/MongoDbCreator.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; using MongoDbGenericRepository.Utils; namespace MongoDbGenericRepository.DataAccess.Create { /// /// A class to insert MongoDb document. /// public class MongoDbCreator : DataAccessBase, IMongoDbCreator { /// /// The construct of the MongoDbCreator class. /// /// A instance. public MongoDbCreator(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } /// public virtual async Task AddOneAsync(TDocument document, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { FormatDocument(document); await HandlePartitioned(document) .InsertOneAsync(document, null, cancellationToken); } /// public virtual void AddOne(TDocument document, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { FormatDocument(document); HandlePartitioned(document) .InsertOne(document, null, cancellationToken); } /// public virtual async Task AddManyAsync(IEnumerable documents, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var documentsList = documents.ToList(); if (!documentsList.Any()) { return; } foreach (var document in documentsList) { FormatDocument(document); } // cannot use typeof(IPartitionedDocument).IsAssignableFrom(typeof(TDocument)), not available in netstandard 1.5 if (documentsList.Any(e => e is IPartitionedDocument)) { foreach (var group in documentsList.GroupBy(e => ((IPartitionedDocument) e).PartitionKey)) { await HandlePartitioned(group.FirstOrDefault()).InsertManyAsync(group.ToList(), null, cancellationToken); } } else { await GetCollection().InsertManyAsync(documentsList, null, cancellationToken); } } /// public virtual void AddMany(IEnumerable documents, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var documentList = documents.ToList(); if (!documentList.Any()) { return; } foreach (var document in documentList) { FormatDocument(document); } // cannot use typeof(IPartitionedDocument).IsAssignableFrom(typeof(TDocument)), not available in netstandard 1.5 if (documentList.Any(e => e is IPartitionedDocument)) { foreach (var group in documentList.GroupBy(e => ((IPartitionedDocument) e).PartitionKey)) { HandlePartitioned(group.FirstOrDefault()).InsertMany(group.ToList(), cancellationToken: cancellationToken); } } else { GetCollection().InsertMany(documentList, cancellationToken: cancellationToken); } } /// /// Sets the value of the document Id if it is not set already. /// /// The document type. /// The type of the primary key. /// The document. protected void FormatDocument(TDocument document) where TDocument : IDocument where TKey : IEquatable { if (document == null) { throw new ArgumentNullException(nameof(document)); } var defaultTKey = default(TKey); if (document.Id == null || (defaultTKey != null && defaultTKey.Equals(document.Id))) { document.Id = IdGenerator.GetId(); } } } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Delete/IMongoDbEraser.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Delete { /// /// The MongoDbEraser interface. used to delete documents from the collections. /// public interface IMongoDbEraser : IDataAccessBase { /// /// Deletes a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to delete. /// An optional cancellation token /// The number of documents deleted. long DeleteOne(TDocument document, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation token /// The number of documents deleted. long DeleteOne(Expression> filter, string partitionKey = default, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to delete. /// The cancellation token /// The number of documents deleted. Task DeleteOneAsync(TDocument document, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token /// The number of documents deleted. Task DeleteOneAsync(Expression> filter, string partitionKey = default, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token /// The number of documents deleted. Task DeleteManyAsync(Expression> filter, string partitionKey = default, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a list of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The list of documents to delete. /// The cancellation token. /// The number of documents deleted. Task DeleteManyAsync(IEnumerable documents, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes a list of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The list of documents to delete. /// The cancellation token /// The number of documents deleted. long DeleteMany(IEnumerable documents, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The Cancellation Token /// The number of documents deleted. long DeleteMany(Expression> filter, string partitionKey = default, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Delete/MongoDbEraser.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Delete { /// public class MongoDbEraser : DataAccessBase, IMongoDbEraser { /// /// The MongoDbEraser constructor. /// /// the MongoDb Context public MongoDbEraser(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } #region Delete TKey /// public virtual long DeleteOne(TDocument document, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", document.Id); return HandlePartitioned(document).DeleteOne(filter, cancellationToken).DeletedCount; } /// public virtual long DeleteOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).DeleteOne(filter, cancellationToken).DeletedCount; } /// public virtual async Task DeleteOneAsync(TDocument document, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", document.Id); return (await HandlePartitioned(document).DeleteOneAsync(filter, cancellationToken)).DeletedCount; } /// public virtual async Task DeleteOneAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return (await HandlePartitioned(partitionKey).DeleteOneAsync(filter, cancellationToken)).DeletedCount; } /// public virtual async Task DeleteManyAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return (await HandlePartitioned(partitionKey).DeleteManyAsync(filter, cancellationToken)).DeletedCount; } /// public virtual async Task DeleteManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { var documentList = documents.ToList(); if (!documentList.Any()) { return 0; } // cannot use typeof(IPartitionedDocument).IsAssignableFrom(typeof(TDocument)), not available in netstandard 1.5 if (documentList.Any(e => e is IPartitionedDocument)) { long deleteCount = 0; foreach (var group in documentList.GroupBy(e => ((IPartitionedDocument) e).PartitionKey)) { var groupIdsToDelete = group.Select(e => e.Id).ToArray(); deleteCount += (await HandlePartitioned(group.FirstOrDefault()) .DeleteManyAsync(x => groupIdsToDelete.Contains(x.Id), cancellationToken)) .DeletedCount; } return deleteCount; } var idsToDelete = documentList.Select(e => e.Id).ToArray(); return (await HandlePartitioned(documentList.FirstOrDefault()).DeleteManyAsync(x => idsToDelete.Contains(x.Id), cancellationToken)) .DeletedCount; } /// public virtual long DeleteMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { var documentList = documents.ToList(); if (!documentList.Any()) { return 0; } // cannot use typeof(IPartitionedDocument).IsAssignableFrom(typeof(TDocument)), not available in netstandard 1.5 if (documentList.Any(e => e is IPartitionedDocument)) { long deleteCount = 0; foreach (var group in documentList.GroupBy(e => ((IPartitionedDocument) e).PartitionKey)) { var groupIdsToDelete = group.Select(e => e.Id).ToArray(); deleteCount += HandlePartitioned(group.FirstOrDefault()).DeleteMany(x => groupIdsToDelete.Contains(x.Id), cancellationToken).DeletedCount; } return deleteCount; } var idsToDelete = documentList.Select(e => e.Id).ToArray(); return HandlePartitioned(documentList.FirstOrDefault()).DeleteMany(x => idsToDelete.Contains(x.Id), cancellationToken).DeletedCount; } /// public virtual long DeleteMany(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).DeleteMany(filter, cancellationToken).DeletedCount; } #endregion } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Index/IMongoDbIndexHandler.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Index { /// /// The MongoDbIndexHandler interface. used to create indexes on collections. /// public interface IMongoDbIndexHandler : IDataAccessBase { /// /// Returns the names of the indexes present on a collection. /// /// The type representing a Document. /// The type of the primary key for a Document. /// An optional partition key /// An optional Cancellation Token. /// A list containing the names of the indexes on on the concerned collection. Task> GetIndexesNamesAsync(string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// An optional cancellation token /// The result of the create index operation. Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// An optional cancellation token. /// The result of the create index operation. Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// An optional cancellation token. /// The result of the create index operation. Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// An optional cancellation token. /// The result of the create index operation. Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The fields we want to index. /// Options for creating an index. /// An optional partition key. /// An optional Cancellation token. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Drops the index given a field name /// /// The type representing a Document. /// The type of the primary key for a Document. /// The name of the index /// An optional partition key /// An optional cancellation token, Task DropIndexAsync(string indexName, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Index/MongoDbIndexHandler.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Index { /// public class MongoDbIndexHandler : DataAccessBase, IMongoDbIndexHandler { /// /// The MongoDbIndexHandler constructor. /// /// The mongo db context public MongoDbIndexHandler(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } /// public virtual async Task> GetIndexesNamesAsync(string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var indexCursor = await HandlePartitioned(partitionKey).Indexes.ListAsync(cancellationToken); var indexes = await indexCursor.ToListAsync(cancellationToken); return indexes.Select(e => e["name"].ToString()).ToList(); } /// public virtual async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var model = new CreateIndexModel( Builders.IndexKeys.Text(field), indexCreationOptions == null ? null : MapIndexOptions(indexCreationOptions) ); return await HandlePartitioned(partitionKey).Indexes .CreateOneAsync( model, cancellationToken: cancellationToken); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = HandlePartitioned(partitionKey); var createOptions = indexCreationOptions == null ? null : MapIndexOptions(indexCreationOptions); var indexKey = Builders.IndexKeys; return await collection.Indexes.CreateOneAsync( new CreateIndexModel(indexKey.Ascending(field), createOptions), cancellationToken: cancellationToken); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = HandlePartitioned(partitionKey); var createOptions = indexCreationOptions == null ? null : MapIndexOptions(indexCreationOptions); var indexKey = Builders.IndexKeys; return await collection.Indexes .CreateOneAsync( new CreateIndexModel(indexKey.Descending(field), createOptions), cancellationToken: cancellationToken); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = HandlePartitioned(partitionKey); var createOptions = indexCreationOptions == null ? null : MapIndexOptions(indexCreationOptions); var indexKey = Builders.IndexKeys; return await collection.Indexes .CreateOneAsync( new CreateIndexModel(indexKey.Hashed(field), createOptions), cancellationToken: cancellationToken); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = HandlePartitioned(partitionKey); var createOptions = indexCreationOptions == null ? null : MapIndexOptions(indexCreationOptions); var listOfDefs = new List>(); foreach (var field in fields) { listOfDefs.Add(Builders.IndexKeys.Text(field)); } return await collection.Indexes .CreateOneAsync( new CreateIndexModel(Builders.IndexKeys.Combine(listOfDefs), createOptions), cancellationToken: cancellationToken); } /// public virtual async Task DropIndexAsync(string indexName, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { await HandlePartitioned(partitionKey).Indexes.DropOneAsync(indexName, cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Read/IMongoDbReader.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Read { /// /// A interface for accessing the Database and its Collections. /// public interface IMongoDbReader : IDataAccessBase { /// /// Asynchronously returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. /// An optional cancellation Token. Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Returns a projected document matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. /// The cancellation token. TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// A LINQ expression filter. /// The projection expression. /// An optional partition key. /// An optional cancellation Token. Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Asynchronously returns a list of projected documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type representing the model you want to project to. /// The document filter. /// The projection expression. /// An optional partition key. /// The cancellation token. List ProjectMany( Expression> filter, Expression> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class; /// /// Groups a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the grouping criteria. /// The type of the projected group. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. /// The cancellation token. List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the grouping criteria. /// The type of the projected group. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. /// The cancellation token. List GroupBy( Expression> filter, Expression> selector, Expression, TProjection>> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Groups filtered a collection of documents given a grouping criteria, /// and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the grouping criteria. /// The type of the projected group. /// A LINQ expression filter. /// The grouping criteria. /// The projected group result. /// The partition key of your document, if any. /// An optional cancellation Token. Task> GroupByAsync( Expression> filter, Expression> selector, Expression, TProjection>> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new(); /// /// Asynchronously returns a paginated list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The property selector. /// Order of the sorting. /// The number of documents you want to skip. Default value is 0. /// The number of documents you want to take. Default value is 50. /// An optional partition key. /// An optional cancellation Token. Task> GetSortedPaginatedAsync( Expression> filter, Expression> sortSelector, bool ascending = true, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a paginated list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The sort definition. /// The number of documents you want to skip. Default value is 0. /// The number of documents you want to take. Default value is 50. /// An optional partition key. /// An optional cancellation Token. Task> GetSortedPaginatedAsync( Expression> filter, SortDefinition sortDefinition, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. /// An optional partition key. /// An optional cancellation Token. Task GetByIdAsync(TKey id, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given its id. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The Id of the document you want to get. /// An optional partition key. /// The cancellation token. TDocument GetById(TKey id, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. /// An optional cancellation Token. Task GetOneAsync( FilterDefinition condition, FindOptions findOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation Token. Task GetOneAsync( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given filter definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. /// The cancellation token. TDocument GetOne( FilterDefinition condition, FindOptions findOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Returns one document given an expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. TDocument GetOne(Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a collection cursor. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. IFindFluent GetCursor(Expression> filter, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partition key. /// An optional cancellation Token. Task AnyAsync( FilterDefinition condition, CountOptions countOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation Token. Task AnyAsync( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partition key. /// The cancellation token. bool Any( FilterDefinition condition, CountOptions countOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Returns true if any of the document of the collection matches the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. bool Any(Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. /// An optional cancellation Token. Task> GetAllAsync( FilterDefinition condition, FindOptions findOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// An optional cancellation Token. Task> GetAllAsync( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb filter option. /// An optional partition key. /// The cancellation token. List GetAll( FilterDefinition condition, FindOptions findOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Returns a list of the documents matching the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. List GetAll( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partitionKey /// An optional cancellation Token. Task CountAsync( FilterDefinition condition, CountOptions countOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partitionKey /// An optional cancellation Token. Task CountAsync( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A mongodb filter definition. /// A mongodb counting option. /// An optional partitionKey /// The cancellation token. long Count( FilterDefinition condition, CountOptions countOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Counts how many documents match the filter condition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partitionKey /// The cancellation token. long Count(Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. /// An optional cancellation Token. Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by descending. /// An optional partitionKey. /// The cancellation token. TDocument GetByMax( Expression> filter, Expression> maxValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. /// An optional cancellation Token. Task GetByMinAsync( Expression> filter, Expression> minValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the /// filter. /// /// The document type. /// The type of the primary key. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. /// The cancellation token. TDocument GetByMin( Expression> filter, Expression> minValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the field for which you want the maximum value. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. /// An optional cancellation Token. Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the maximum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partitionKey. /// The cancellation token. TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. /// An optional cancellation Token. Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Gets the minimum value of a property in a mongodb collections that is satisfying the filter. /// /// The document type. /// The type of the primary key. /// The type of the value used to order the query. /// A LINQ expression filter. /// A property selector to order by ascending. /// An optional partition key. /// The cancellation token. TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. /// An optional cancellation Token. Task SumByAsync( Expression> filter, Expression> selector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. /// An optional cancellation Token. Task SumByAsync( Expression> filter, Expression> selector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. int SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable; /// /// Sums the values of a selected field for a given filtered collection of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The field you want to sum. /// The partition key of your document, if any. decimal SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Read/MongoDbReader.GroupBy.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Read { public partial class MongoDbReader { /// public virtual List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { return HandlePartitioned(partitionKey) .Aggregate() .Group(groupingCriteria, groupProjection) .ToList(cancellationToken); } /// public virtual List GroupBy( Expression> filter, Expression> selector, Expression, TProjection>> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { var collection = HandlePartitioned(partitionKey); return collection.Aggregate() .Match(Builders.Filter.Where(filter)) .Group(selector, projection) .ToList(cancellationToken); } /// public virtual async Task> GroupByAsync( Expression> filter, Expression> selector, Expression, TProjection>> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { var collection = HandlePartitioned(partitionKey); return await collection.Aggregate() .Match(Builders.Filter.Where(filter)) .Group(selector, projection) .ToListAsync(cancellationToken); } /// public virtual async Task> GetSortedPaginatedAsync( Expression> filter, Expression> sortSelector, bool ascending = true, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var sorting = ascending ? Builders.Sort.Ascending(sortSelector) : Builders.Sort.Descending(sortSelector); return await HandlePartitioned(partitionKey) .Find(filter) .Sort(sorting) .Skip(skipNumber) .Limit(takeNumber) .ToListAsync(cancellationToken); } /// public virtual async Task> GetSortedPaginatedAsync( Expression> filter, SortDefinition sortDefinition, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await HandlePartitioned(partitionKey) .Find(filter) .Sort(sortDefinition) .Skip(skipNumber) .Limit(takeNumber) .ToListAsync(cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Read/MongoDbReader.Main.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDB.Driver.Linq; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Read { /// /// A class to read MongoDb document. /// public partial class MongoDbReader : DataAccessBase, IMongoDbReader { /// /// The construct of the MongoDbReader class. /// /// A instance. public MongoDbReader(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } #region Read TKey /// public virtual async Task GetByIdAsync(TKey id, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", id); return await HandlePartitioned(partitionKey).Find(filter).FirstOrDefaultAsync(cancellationToken); } /// public virtual TDocument GetById(TKey id, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", id); return HandlePartitioned(partitionKey).Find(filter).FirstOrDefault(cancellationToken); } /// public virtual Task GetOneAsync( FilterDefinition condition, FindOptions findOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).Find(condition, findOption).FirstOrDefaultAsync(cancellationToken); } /// public virtual TDocument GetOne( FilterDefinition condition, FindOptions findOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).Find(condition, findOption).FirstOrDefault(cancellationToken); } /// public virtual async Task GetOneAsync( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await HandlePartitioned(partitionKey).Find(filter).FirstOrDefaultAsync(cancellationToken); } /// public virtual TDocument GetOne( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).Find(filter).FirstOrDefault(cancellationToken); } /// public virtual IFindFluent GetCursor(Expression> filter, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).Find(filter); } /// public virtual async Task AnyAsync( FilterDefinition condition, CountOptions countOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var count = await HandlePartitioned(partitionKey).CountDocumentsAsync(condition, countOption, cancellationToken); return count > 0; } /// public virtual bool Any( FilterDefinition condition, CountOptions countOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var count = HandlePartitioned(partitionKey).CountDocuments(condition, countOption, cancellationToken); return count > 0; } /// public virtual async Task AnyAsync( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var count = await HandlePartitioned(partitionKey).CountDocumentsAsync(filter, cancellationToken: cancellationToken); return count > 0; } /// public virtual bool Any( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var count = HandlePartitioned(partitionKey).CountDocuments(filter, cancellationToken: cancellationToken); return count > 0; } /// public virtual Task> GetAllAsync( FilterDefinition condition, FindOptions findOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).Find(condition, findOption).ToListAsync(cancellationToken); } /// public virtual List GetAll( FilterDefinition condition, FindOptions findOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).Find(condition, findOption).ToList(cancellationToken); } /// public virtual async Task> GetAllAsync( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await HandlePartitioned(partitionKey).Find(filter).ToListAsync(cancellationToken); } /// public virtual List GetAll( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).Find(filter).ToList(cancellationToken); } /// public virtual Task CountAsync( FilterDefinition condition, CountOptions countOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).CountDocumentsAsync(condition, countOption, cancellationToken); } /// public virtual long Count( FilterDefinition condition, CountOptions countOption = null, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).CountDocuments(condition, countOption, cancellationToken); } /// public virtual async Task CountAsync( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await HandlePartitioned(partitionKey).CountDocumentsAsync(filter, cancellationToken: cancellationToken); } /// public virtual long Count( Expression> filter, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return HandlePartitioned(partitionKey).Find(filter).CountDocuments(cancellationToken); } #endregion #region Min / Max /// public virtual async Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await GetCollection(partitionKey).Find(Builders.Filter.Where(filter)) .SortByDescending(maxValueSelector) .Limit(1) .FirstOrDefaultAsync(cancellationToken); } /// public virtual TDocument GetByMax( Expression> filter, Expression> maxValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return GetCollection(partitionKey).Find(Builders.Filter.Where(filter)) .SortByDescending(maxValueSelector) .Limit(1) .FirstOrDefault(cancellationToken); } /// public virtual async Task GetByMinAsync( Expression> filter, Expression> minValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await GetCollection(partitionKey).Find(Builders.Filter.Where(filter)) .SortBy(minValueSelector) .Limit(1) .FirstOrDefaultAsync(cancellationToken); } /// public virtual TDocument GetByMin( Expression> filter, Expression> minValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return GetCollection(partitionKey).Find(Builders.Filter.Where(filter)) .SortBy(minValueSelector) .Limit(1) .FirstOrDefault(cancellationToken); } /// public virtual async Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await GetMaxMongoQuery(filter, maxValueSelector, partitionKey) .Project(maxValueSelector) .FirstOrDefaultAsync(cancellationToken); } /// public virtual TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return GetMaxMongoQuery(filter, maxValueSelector, partitionKey) .Project(maxValueSelector) .FirstOrDefault(cancellationToken); } /// public virtual async Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await GetMinMongoQuery(filter, minValueSelector, partitionKey).Project(minValueSelector) .FirstOrDefaultAsync(cancellationToken); } /// public virtual TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return GetMinMongoQuery(filter, minValueSelector, partitionKey).Project(minValueSelector) .FirstOrDefault(cancellationToken); } #endregion Min / Max #region Sum TKey /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await GetQuery(filter, partitionKey).SumAsync(selector, cancellationToken); } /// public virtual int SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return GetQuery(filter, partitionKey).Sum(selector); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await GetQuery(filter, partitionKey).SumAsync(selector, cancellationToken); } /// public virtual decimal SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return GetQuery(filter, partitionKey).Sum(selector); } #endregion Sum TKey } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Read/MongoDbReader.Project.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Read { public partial class MongoDbReader { /// public virtual async Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await HandlePartitioned(partitionKey) .Find(filter) .Project(projection) .FirstOrDefaultAsync(cancellationToken); } /// public virtual async Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await HandlePartitioned(partitionKey).Find(filter) .Project(projection) .ToListAsync(cancellationToken); } /// public virtual TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return HandlePartitioned(partitionKey).Find(filter) .Project(projection) .FirstOrDefault(cancellationToken); } /// public virtual List ProjectMany( Expression> filter, Expression> projection, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return HandlePartitioned(partitionKey).Find(filter) .Project(projection) .ToList(cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Update/IMongoDbUpdater.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Update { /// /// A interface for updating documents in MongoDb. /// public interface IMongoDbUpdater : IDataAccessBase { /// /// Asynchronously Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document with the modifications you want to persist. /// An optional cancellation token. Task UpdateOneAsync(TDocument modifiedDocument, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to modify. /// The update definition for the document. /// An optional cancellation token. Task UpdateOneAsync( TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. /// An optional cancellation token. Task UpdateOneAsync( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// An optional cancellation token. Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// An optional cancellation token. Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document with the modifications you want to persist. /// The optional cancellation token. /// Task UpdateOneAsync(IClientSessionHandle session, TDocument modifiedDocument, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document to modify. /// The update definition. /// The optional cancellation token. /// Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The document to modify. /// The field to update. /// The value of the field. /// The optional cancellation token. /// Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// The optional cancellation token. /// Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// The optional cancellation token. /// Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document with the modifications you want to persist. /// The optional cancellation token. bool UpdateOne(TDocument modifiedDocument, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to modify. /// The update definition for the document. /// The optional cancellation token. bool UpdateOne(TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. /// The optional cancellation token. bool UpdateOne( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The optional cancellation token. bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The optional cancellation token. bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document with the modifications you want to persist. /// The optional cancellation token. /// bool UpdateOne(IClientSessionHandle session, TDocument modifiedDocument, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The client session. /// The document to modify. /// The update definition. /// The optional cancellation token. /// bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The document to modify. /// The field to update. /// The value of the field. /// The optional cancellation token. /// bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// The optional cancellation token. /// bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// Updates a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field to update. /// The client session. /// The filter for the update. /// The field to update. /// The value of the field. /// The optional partition key. /// The optional cancellation token. /// bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The optional cancellation token. Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The optional cancellation token. Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, apply the update definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// the update definition /// The value of the partition key. /// The optional cancellation token. Task UpdateManyAsync( Expression> filter, UpdateDefinition update, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, apply the update definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition. /// The value of the partition key. /// The optional cancellation token. Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The optional cancellation token. long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The optional cancellation token. long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, apply the update definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition. /// The value of the partition key. /// The optional cancellation token. long UpdateMany( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; /// /// For the entities selected by the filter, apply the update definition. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document filter. /// The update definition. /// The value of the partition key. /// The optional cancellation token. long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Update/MongoDbUpdater.ClientSession.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Update { public partial class MongoDbUpdater { /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, TDocument modifiedDocument, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", modifiedDocument.Id); var updateRes = await HandlePartitioned(modifiedDocument) .ReplaceOneAsync(session, filter, modifiedDocument, cancellationToken: cancellationToken) .ConfigureAwait(false); return updateRes.ModifiedCount == 1; } /// public virtual bool UpdateOne(IClientSessionHandle session, TDocument modifiedDocument, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", modifiedDocument.Id); var updateRes = HandlePartitioned(modifiedDocument) .ReplaceOne(session, filter, modifiedDocument, cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", documentToModify.Id); var updateRes = await HandlePartitioned(documentToModify).UpdateOneAsync(session, filter, update, null, cancellationToken) .ConfigureAwait(false); return updateRes.ModifiedCount == 1; } /// public virtual bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", documentToModify.Id); var updateRes = HandlePartitioned(documentToModify).UpdateOne(session, filter, update, null, cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", documentToModify.Id); var updateRes = await HandlePartitioned(documentToModify) .UpdateOneAsync(session, filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken) .ConfigureAwait(false); return updateRes.ModifiedCount == 1; } /// public virtual bool UpdateOne( IClientSessionHandle session, TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", documentToModify.Id); var updateRes = HandlePartitioned(documentToModify).UpdateOne( session, filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual async Task UpdateOneAsync( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection() : GetCollection(partitionKey); var updateRes = await collection.UpdateOneAsync(session, filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken) .ConfigureAwait(false); return updateRes.ModifiedCount == 1; } /// public virtual Task UpdateOneAsync( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return UpdateOneAsync(session, Builders.Filter.Where(filter), field, value, partitionKey, cancellationToken); } /// public virtual bool UpdateOne( IClientSessionHandle session, FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection() : GetCollection(partitionKey); var updateRes = collection.UpdateOne(session, filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual bool UpdateOne( IClientSessionHandle session, Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(session, Builders.Filter.Where(filter), field, value, partitionKey, cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/DataAccess/Update/MongoDbUpdater.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Base; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository.DataAccess.Update { /// /// The MongoDb updater. /// public partial class MongoDbUpdater : DataAccessBase, IMongoDbUpdater { /// /// Constructor /// /// public MongoDbUpdater(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } /// public virtual async Task UpdateOneAsync(TDocument modifiedDocument, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", modifiedDocument.Id); var updateRes = await HandlePartitioned(modifiedDocument) .ReplaceOneAsync(filter, modifiedDocument, cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual bool UpdateOne(TDocument modifiedDocument, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", modifiedDocument.Id); var updateRes = HandlePartitioned(modifiedDocument).ReplaceOne(filter, modifiedDocument, cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual async Task UpdateOneAsync( TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", documentToModify.Id); var updateRes = await HandlePartitioned(documentToModify).UpdateOneAsync(filter, update, cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual bool UpdateOne( TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", documentToModify.Id); var updateRes = HandlePartitioned(documentToModify).UpdateOne(filter, update, cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual async Task UpdateOneAsync( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", documentToModify.Id); var updateRes = await HandlePartitioned(documentToModify).UpdateOneAsync( filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual bool UpdateOne( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var filter = Builders.Filter.Eq("Id", documentToModify.Id); var updateRes = HandlePartitioned(documentToModify).UpdateOne( filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection() : GetCollection(partitionKey); var updateRes = await collection.UpdateOneAsync(filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await UpdateOneAsync(Builders.Filter.Where(filter), field, value, partitionKey, cancellationToken); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection() : GetCollection(partitionKey); var updateRes = collection.UpdateOne(filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken); return updateRes.ModifiedCount == 1; } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return UpdateOne(Builders.Filter.Where(filter), field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(Builders.Filter.Where(filter), field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection() : GetCollection(partitionKey); var updateRes = await collection.UpdateManyAsync(filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken); return updateRes.ModifiedCount; } /// public virtual async Task UpdateManyAsync( Expression> filter, UpdateDefinition update, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await UpdateManyAsync(Builders.Filter.Where(filter), update, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection() : GetCollection(partitionKey); var updateRes = await collection.UpdateManyAsync(filter, updateDefinition, cancellationToken: cancellationToken); return updateRes.ModifiedCount; } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return UpdateMany(Builders.Filter.Where(filter), field, value, partitionKey, cancellationToken); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection() : GetCollection(partitionKey); var updateRes = collection.UpdateMany(filter, Builders.Update.Set(field, value), cancellationToken: cancellationToken); return updateRes.ModifiedCount; } /// public virtual long UpdateMany( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection() : GetCollection(partitionKey); var updateRes = collection.UpdateMany(filter, updateDefinition, cancellationToken: cancellationToken); return updateRes.ModifiedCount; } /// public virtual long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection() : GetCollection(partitionKey); var updateRes = collection.UpdateMany(filter, updateDefinition, cancellationToken: cancellationToken); return updateRes.ModifiedCount; } } } ================================================ FILE: MongoDbGenericRepository/IBaseMongoRepository.Create.cs ================================================ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The IBaseMongoRepository_Create interface to expose document creation functionality /// with document having an Id of type Guid. /// public interface IBaseMongoRepository_Create : IBaseMongoRepository_Create { /// /// Asynchronously adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to add. Task AddOneAsync(TDocument document) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to add. /// An optional cancellation Token. Task AddOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to add. void AddOne(TDocument document) where TDocument : IDocument where TKey : IEquatable; /// /// Adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to add. /// The cancellation token. void AddOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The documents you want to add. Task AddManyAsync(IEnumerable documents) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The documents you want to add. /// An optional cancellation Token. Task AddManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The documents you want to add. void AddMany(IEnumerable documents) where TDocument : IDocument where TKey : IEquatable; /// /// Adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The documents you want to add. /// The cancellation token void AddMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/IBaseMongoRepository.Delete.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Mongo Repository Delete interface. used to delete documents from the collections. /// public interface IBaseMongoRepository_Delete : IBaseMongoRepository_Delete { /// /// Deletes a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to delete. /// The number of documents deleted. long DeleteOne(TDocument document) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes a document. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to delete. /// The cancellation token. /// The number of documents deleted. long DeleteOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The number of documents deleted. long DeleteOne(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The cancellation token /// The number of documents deleted. long DeleteOne(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The number of documents deleted. long DeleteOne(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. /// The number of documents deleted. long DeleteOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to delete. /// The number of documents deleted. Task DeleteOneAsync(TDocument document) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The document you want to delete. /// The Cancellation token /// The number of documents deleted. Task DeleteOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The number of documents deleted. Task DeleteOneAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The cancellation token. /// The number of documents deleted. Task DeleteOneAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The number of documents deleted. Task DeleteOneAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. /// The number of documents deleted. Task DeleteOneAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The number of documents deleted. Task DeleteManyAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The cancellation token. /// The number of documents deleted. Task DeleteManyAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The number of documents deleted. Task DeleteManyAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. /// The number of documents deleted. Task DeleteManyAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a list of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The list of documents to delete. /// The number of documents deleted. Task DeleteManyAsync(IEnumerable documents) where TDocument : IDocument where TKey : IEquatable; /// /// Asynchronously deletes a list of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The list of documents to delete. /// The cancellation token. /// The number of documents deleted. Task DeleteManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes a list of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The list of documents to delete. /// The number of documents deleted. long DeleteMany(IEnumerable documents) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes a list of documents. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The list of documents to delete. /// The cancellation token /// The number of documents deleted. long DeleteMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The number of documents deleted. long DeleteMany(Expression> filter) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// The cancellation token. /// The number of documents deleted. long DeleteMany(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The number of documents deleted. long DeleteMany(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token /// The number of documents deleted. long DeleteMany(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/IBaseMongoRepository.Index.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The interface exposing index management functionality for Guid Keyed repositories. /// public interface IBaseMongoRepository_Index : IBaseMongoRepository_Index { /// /// Returns the names of the indexes present on a collection. /// /// The type representing a Document. /// The type of the primary key for a Document. /// A list containing the names of the indexes on on the concerned collection. Task> GetIndexesNamesAsync() where TDocument : IDocument where TKey : IEquatable; /// /// Returns the names of the indexes present on a collection. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The cancellation token /// A list containing the names of the indexes on on the concerned collection. Task> GetIndexesNamesAsync(CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Returns the names of the indexes present on a collection. /// /// The type representing a Document. /// The type of the primary key for a Document. /// An optional partition key /// A list containing the names of the indexes on on the concerned collection. Task> GetIndexesNamesAsync(string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Returns the names of the indexes present on a collection. /// /// The type representing a Document. /// The type of the primary key for a Document. /// An optional partition key /// The cancellation token /// A list containing the names of the indexes on on the concerned collection. Task> GetIndexesNamesAsync(string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field) where TDocument : IDocument where TKey : IEquatable; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// The cancellation token /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// An optional partition key /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// An optional partition key /// The cancellation token /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// The cancellation token /// The result of the create index operation. Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// The result of the create index operation. Task CreateAscendingIndexAsync(Expression> field) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// The cancellation token. /// The result of the create index operation. Task CreateAscendingIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateAscendingIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// The cancellation token. /// The result of the create index operation. Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// An optional partition key. /// The result of the create index operation. Task CreateAscendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateAscendingIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// The result of the create index operation. Task CreateDescendingIndexAsync(Expression> field) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// The cancellation token. /// The result of the create index operation. Task CreateDescendingIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateDescendingIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// The cancellation token. /// The result of the create index operation. Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// An optional partition key. /// The result of the create index operation. Task CreateDescendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateDescendingIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// The result of the create index operation. Task CreateHashedIndexAsync(Expression> field) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// The cancellation token. /// The result of the create index operation. Task CreateHashedIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateHashedIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// The cancellation token. /// The result of the create index operation. Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// An optional partition key. /// The result of the create index operation. Task CreateHashedIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateHashedIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The fields we want to index. /// The result of the create index operation. Task CreateCombinedTextIndexAsync(IEnumerable>> fields) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The fields we want to index. /// The cancellation token. /// The result of the create index operation. Task CreateCombinedTextIndexAsync(IEnumerable>> fields, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The fields we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The fields we want to index. /// Options for creating an index. /// The cancellation token. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The fields we want to index. /// An optional partition key. /// The result of the create index operation. Task CreateCombinedTextIndexAsync(IEnumerable>> fields, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The fields we want to index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The fields we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The type of the primary key for a Document. /// The fields we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Drops the index given a field name /// /// The type representing a Document. /// The type of the primary key for a Document. /// The name of the index Task DropIndexAsync(string indexName) where TDocument : IDocument where TKey : IEquatable; /// /// Drops the index given a field name /// /// The type representing a Document. /// The type of the primary key for a Document. /// The name of the index /// The cancellation token Task DropIndexAsync(string indexName, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; /// /// Drops the index given a field name /// /// The type representing a Document. /// The type of the primary key for a Document. /// The name of the index /// An optional partition key Task DropIndexAsync(string indexName, string partitionKey) where TDocument : IDocument where TKey : IEquatable; /// /// Drops the index given a field name /// /// The type representing a Document. /// The type of the primary key for a Document. /// The name of the index /// An optional partition key /// The cancellation token Task DropIndexAsync(string indexName, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable; } } ================================================ FILE: MongoDbGenericRepository/Internals/RepositorySerializationProvider.cs ================================================ using System; using System.Collections.Concurrent; using MongoDB.Bson.Serialization; namespace MongoDbGenericRepository.Internals { /// /// An that can handle multiple serializer registration calls. /// internal class RepositorySerializationProvider : IBsonSerializationProvider { private static volatile RepositorySerializationProvider _instance; private static readonly object LockObject = new object(); private readonly ConcurrentDictionary _cache; private RepositorySerializationProvider() { _cache = new ConcurrentDictionary(); } public static RepositorySerializationProvider Instance { get { if (_instance == null) { lock (LockObject) { if (_instance == null) { _instance = new RepositorySerializationProvider(); BsonSerializer.RegisterSerializationProvider(_instance); } } } return _instance; } } /// public IBsonSerializer GetSerializer(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } return _cache.TryGetValue(type, out var serializer) ? serializer : null; } internal void RegisterSerializer(IBsonSerializer serializer) => RegisterSerializer(typeof(T), serializer); internal void RegisterSerializer(Type type, IBsonSerializer serializer) => _cache.TryAdd(type, serializer); } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/BaseMongoRepository.TKey.Create.cs ================================================ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Create; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. /// Its constructor must be given a connection string and a database name. /// public abstract partial class BaseMongoRepository : IBaseMongoRepository_Create where TKey : IEquatable { private IMongoDbCreator _mongoDbCreator; /// /// The MongoDb accessor to insert data. /// protected virtual IMongoDbCreator MongoDbCreator { get { if (_mongoDbCreator == null) { lock (_initLock) { if (_mongoDbCreator == null) { _mongoDbCreator = new MongoDbCreator(MongoDbContext); } } } return _mongoDbCreator; } set => _mongoDbCreator = value; } /// public virtual async Task AddOneAsync(TDocument document) where TDocument : IDocument { await AddOneAsync(document, CancellationToken.None); } /// public virtual async Task AddOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument { await MongoDbCreator.AddOneAsync(document, cancellationToken); } /// public virtual void AddOne(TDocument document) where TDocument : IDocument { AddOne(document, CancellationToken.None); } /// public virtual void AddOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument { MongoDbCreator.AddOne(document, cancellationToken); } /// public virtual async Task AddManyAsync(IEnumerable documents) where TDocument : IDocument { await AddManyAsync(documents, CancellationToken.None); } /// public virtual async Task AddManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument { await MongoDbCreator.AddManyAsync(documents, cancellationToken); } /// public virtual void AddMany(IEnumerable documents) where TDocument : IDocument { AddMany(documents, CancellationToken.None); } /// public virtual void AddMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument { MongoDbCreator.AddMany(documents, cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/BaseMongoRepository.TKey.Delete.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Delete; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { public abstract partial class BaseMongoRepository : IBaseMongoRepository_Delete where TKey : IEquatable { private IMongoDbEraser _mongoDbEraser; /// /// The MongoDb accessor to delete data. /// protected virtual IMongoDbEraser MongoDbEraser { get { if (_mongoDbEraser != null) { return _mongoDbEraser; } lock (_initLock) { if (_mongoDbEraser == null) { _mongoDbEraser = new MongoDbEraser(MongoDbContext); } } return _mongoDbEraser; } set => _mongoDbEraser = value; } /// public virtual long DeleteOne(TDocument document) where TDocument : IDocument { return DeleteOne(document, CancellationToken.None); } /// public virtual long DeleteOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbEraser.DeleteOne(document, cancellationToken); } /// public virtual long DeleteOne(Expression> filter) where TDocument : IDocument { return DeleteOne(filter, null, CancellationToken.None); } /// public virtual long DeleteOne(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return DeleteOne(filter, null, cancellationToken); } /// public virtual long DeleteOne(Expression> filter, string partitionKey) where TDocument : IDocument { return DeleteOne(filter, partitionKey, CancellationToken.None); } /// public virtual long DeleteOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbEraser.DeleteOne(filter, partitionKey, cancellationToken); } /// public virtual async Task DeleteOneAsync(TDocument document) where TDocument : IDocument { return await DeleteOneAsync(document, CancellationToken.None); } /// public virtual async Task DeleteOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbEraser.DeleteOneAsync(document, cancellationToken); } /// public virtual async Task DeleteOneAsync(Expression> filter) where TDocument : IDocument { return await DeleteOneAsync(filter, null, CancellationToken.None); } /// public virtual async Task DeleteOneAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return await DeleteOneAsync(filter, null, cancellationToken); } /// public virtual async Task DeleteOneAsync(Expression> filter, string partitionKey) where TDocument : IDocument { return await DeleteOneAsync(filter, partitionKey, CancellationToken.None); } /// public virtual async Task DeleteOneAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbEraser.DeleteOneAsync(filter, partitionKey, cancellationToken); } /// public virtual async Task DeleteManyAsync(IEnumerable documents) where TDocument : IDocument { return await DeleteManyAsync(documents, CancellationToken.None); } /// public virtual async Task DeleteManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbEraser.DeleteManyAsync(documents, cancellationToken); } /// public async Task DeleteManyAsync(Expression> filter) where TDocument : IDocument { return await DeleteManyAsync(filter, null, CancellationToken.None); } /// public async Task DeleteManyAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return await DeleteManyAsync(filter, null, cancellationToken); } /// public virtual async Task DeleteManyAsync(Expression> filter, string partitionKey) where TDocument : IDocument { return await DeleteManyAsync(filter, partitionKey, CancellationToken.None); } /// public virtual async Task DeleteManyAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbEraser.DeleteManyAsync(filter, partitionKey, cancellationToken); } /// public virtual long DeleteMany(IEnumerable documents) where TDocument : IDocument { return DeleteMany(documents, CancellationToken.None); } /// public virtual long DeleteMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbEraser.DeleteMany(documents, cancellationToken); } /// public virtual long DeleteMany(Expression> filter) where TDocument : IDocument { return DeleteMany(filter, null, CancellationToken.None); } /// public virtual long DeleteMany(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return DeleteMany(filter, null, cancellationToken); } /// public virtual long DeleteMany(Expression> filter, string partitionKey) where TDocument : IDocument { return DeleteMany(filter, partitionKey, CancellationToken.None); } /// public virtual long DeleteMany(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbEraser.DeleteMany(filter, partitionKey, cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/BaseMongoRepository.TKey.Index.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.DataAccess.Index; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. /// Its constructor must be given a connection string and a database name. /// public abstract partial class BaseMongoRepository : IBaseMongoRepository_Index where TKey : IEquatable { private IMongoDbIndexHandler _mongoDbIndexHandler; /// /// The MongoDb accessor to manage indexes. /// protected virtual IMongoDbIndexHandler MongoDbIndexHandler { get { if (_mongoDbIndexHandler != null) { return _mongoDbIndexHandler; } lock (_initLock) { if (_mongoDbIndexHandler == null) { _mongoDbIndexHandler = new MongoDbIndexHandler(MongoDbContext); } } return _mongoDbIndexHandler; } set => _mongoDbIndexHandler = value; } /// public virtual async Task> GetIndexesNamesAsync() where TDocument : IDocument { return await MongoDbIndexHandler.GetIndexesNamesAsync(); } /// public virtual async Task> GetIndexesNamesAsync(CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbIndexHandler.GetIndexesNamesAsync(cancellationToken: cancellationToken); } /// public virtual async Task> GetIndexesNamesAsync(string partitionKey) where TDocument : IDocument { return await MongoDbIndexHandler.GetIndexesNamesAsync(partitionKey); } /// public virtual async Task> GetIndexesNamesAsync(string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbIndexHandler.GetIndexesNamesAsync(partitionKey, cancellationToken); } /// public virtual async Task CreateTextIndexAsync(Expression> field) where TDocument : IDocument { return await CreateTextIndexAsync(field, null, null, CancellationToken.None); } /// public virtual async Task CreateTextIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateTextIndexAsync(field, null, null, cancellationToken); } /// public virtual async Task CreateTextIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateTextIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateTextIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateTextIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateTextIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument { return await CreateTextIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateTextIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateTextIndexAsync(field, null, partitionKey, cancellationToken); } /// public virtual async Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbIndexHandler.CreateTextIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task CreateAscendingIndexAsync(Expression> field) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, null, null, CancellationToken.None); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, null, null, cancellationToken); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateAscendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, null, partitionKey, cancellationToken); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateAscendingIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbIndexHandler.CreateAscendingIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task CreateDescendingIndexAsync(Expression> field) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, null, null, CancellationToken.None); } /// public virtual async Task CreateDescendingIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, null, null, cancellationToken); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateDescendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, null, partitionKey, cancellationToken); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateDescendingIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbIndexHandler.CreateDescendingIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task CreateHashedIndexAsync(Expression> field) where TDocument : IDocument { return await CreateHashedIndexAsync(field, null, null, CancellationToken.None); } /// public virtual async Task CreateHashedIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateHashedIndexAsync(field, null, null, cancellationToken); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateHashedIndexAsync(field, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateHashedIndexAsync(field, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateHashedIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument { return await CreateHashedIndexAsync(field, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateHashedIndexAsync(field, null, partitionKey, cancellationToken); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateHashedIndexAsync(field, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbIndexHandler.CreateHashedIndexAsync(field, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task CreateCombinedTextIndexAsync(IEnumerable>> fields) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, null, null, CancellationToken.None); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, null, null, cancellationToken); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, null, CancellationToken.None); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, null, cancellationToken); } /// public virtual async Task CreateCombinedTextIndexAsync(IEnumerable>> fields, string partitionKey) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, null, partitionKey, CancellationToken.None); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, null, partitionKey, cancellationToken); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument { return await CreateCombinedTextIndexAsync(fields, indexCreationOptions, partitionKey, CancellationToken.None); } /// public virtual async Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbIndexHandler.CreateCombinedTextIndexAsync(fields, indexCreationOptions, partitionKey, cancellationToken); } /// public virtual async Task DropIndexAsync(string indexName) where TDocument : IDocument { await DropIndexAsync(indexName, null, CancellationToken.None); } /// public virtual async Task DropIndexAsync(string indexName, CancellationToken cancellationToken) where TDocument : IDocument { await DropIndexAsync(indexName, null, cancellationToken); } /// public virtual async Task DropIndexAsync(string indexName, string partitionKey) where TDocument : IDocument { await DropIndexAsync(indexName, partitionKey, CancellationToken.None); } /// public virtual async Task DropIndexAsync(string indexName, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { await MongoDbIndexHandler.DropIndexAsync(indexName, partitionKey, cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/BaseMongoRepository.TKey.Main.cs ================================================ using System; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. /// Its constructor must be given a connection string and a database name. /// /// The type of the document Id. public abstract partial class BaseMongoRepository : ReadOnlyMongoRepository, IBaseMongoRepository where TKey : IEquatable { private readonly object _initLock = new object(); /// /// The constructor taking a connection string and a database name. /// /// The connection string of the MongoDb server. /// The name of the database against which you want to perform operations. protected BaseMongoRepository(string connectionString, string databaseName = null) : base(connectionString, databaseName) { } /// /// The constructor taking a . /// /// A mongodb context implementing protected BaseMongoRepository(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } /// /// The constructor taking a . /// /// A mongodb context implementing protected BaseMongoRepository(IMongoDatabase mongoDatabase) : base(mongoDatabase) { } /// /// Gets a collections for a potentially partitioned document type. /// /// The document type. /// The collection partition key. /// protected virtual IMongoCollection HandlePartitioned(string partitionKey) where TDocument : IDocument { if (!string.IsNullOrEmpty(partitionKey)) { return GetCollection(partitionKey); } return GetCollection(); } /// /// Gets a collections for the type TDocument with a partition key. /// /// The document type. /// The collection partition key. /// protected virtual IMongoCollection GetCollection(string partitionKey = null) where TDocument : IDocument { return MongoDbContext.GetCollection(partitionKey); } } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/BaseMongoRepository.TKey.ReadOnly.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Read; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. /// Its constructor must be given a connection string and a database name. /// public abstract class ReadOnlyMongoRepository : IReadOnlyMongoRepository where TKey : IEquatable { /// /// The constructor taking a connection string and a database name. /// /// The connection string of the MongoDb server. /// The name of the database against which you want to perform operations. protected ReadOnlyMongoRepository(string connectionString, string databaseName = null) { SetupMongoDbContext(connectionString, databaseName); } /// /// The constructor taking a . /// /// A mongodb context implementing protected ReadOnlyMongoRepository(IMongoDatabase mongoDatabase) : this(new MongoDbContext(mongoDatabase)) { } /// /// The constructor taking a . /// /// A mongodb context implementing protected ReadOnlyMongoRepository(IMongoDbContext mongoDbContext) { SetupMongoDbContext(mongoDbContext); } /// /// The MongoDbContext /// protected IMongoDbContext MongoDbContext { get; set; } /// /// A MongoDb Reader for read operations /// protected IMongoDbReader MongoDbReader { get; set; } /// /// The connection string. /// public string ConnectionString { get; protected set; } /// /// The database name. /// public string DatabaseName { get; protected set; } /// public virtual List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection) where TDocument : IDocument where TProjection : class, new() { return GroupBy(groupingCriteria, groupProjection, null, CancellationToken.None); } /// public virtual List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class, new() { return GroupBy(groupingCriteria, groupProjection, null, cancellationToken); } /// public virtual List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey) where TDocument : IDocument where TProjection : class, new() { return GroupBy(groupingCriteria, groupProjection, partitionKey, CancellationToken.None); } /// public virtual List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class, new() { return MongoDbReader.GroupBy(groupingCriteria, groupProjection, partitionKey, cancellationToken); } /// public virtual List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection) where TDocument : IDocument where TProjection : class, new() { return GroupBy(filter, groupingCriteria, groupProjection, null, CancellationToken.None); } /// public virtual List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class, new() { return GroupBy(filter, groupingCriteria, groupProjection, null, cancellationToken); } /// public virtual List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey) where TDocument : IDocument where TProjection : class, new() { return GroupBy(filter, groupingCriteria, groupProjection, partitionKey, CancellationToken.None); } /// public virtual List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class, new() { return MongoDbReader.GroupBy(filter, groupingCriteria, groupProjection, partitionKey, cancellationToken); } /// public virtual async Task> GetSortedPaginatedAsync( Expression> filter, Expression> sortSelector, bool ascending = true, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument { return await MongoDbReader.GetSortedPaginatedAsync( filter, sortSelector, ascending, skipNumber, takeNumber, partitionKey, cancellationToken); } /// public virtual async Task> GetSortedPaginatedAsync( Expression> filter, SortDefinition sortDefinition, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument { return await MongoDbReader.GetSortedPaginatedAsync( filter, sortDefinition, skipNumber, takeNumber, partitionKey, cancellationToken); } /// /// Setups the repository with a . /// /// protected void SetupMongoDbContext(IMongoDbContext mongoDbContext) { MongoDbContext = MongoDbContext ?? mongoDbContext; MongoDbReader = MongoDbReader ?? new MongoDbReader(MongoDbContext); } /// /// Setups the repository with a connection string and a database name. /// /// /// /// The database name. If the database name is null or whitespace it is taken from the /// connection string /// protected void SetupMongoDbContext(string connectionString, string databaseName) { if (string.IsNullOrWhiteSpace(databaseName)) { var mongoUrl = new MongoUrl(connectionString); databaseName = mongoUrl.DatabaseName; } ConnectionString = connectionString; DatabaseName = databaseName; SetupMongoDbContext(new MongoDbContext(connectionString, databaseName)); } #region Read /// public async Task GetByIdAsync(TKey id) where TDocument : IDocument { return await GetByIdAsync(id, null, CancellationToken.None); } /// public async Task GetByIdAsync(TKey id, CancellationToken cancellationToken) where TDocument : IDocument { return await GetByIdAsync(id, null, cancellationToken); } /// public async Task GetByIdAsync(TKey id, string partitionKey) where TDocument : IDocument { return await GetByIdAsync(id, partitionKey, CancellationToken.None); } /// public async Task GetByIdAsync(TKey id, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.GetByIdAsync(id, partitionKey, cancellationToken); } /// public TDocument GetById(TKey id) where TDocument : IDocument { return GetById(id, null, CancellationToken.None); } /// public TDocument GetById(TKey id, CancellationToken cancellationToken) where TDocument : IDocument { return GetById(id, null, cancellationToken); } /// public TDocument GetById(TKey id, string partitionKey) where TDocument : IDocument { return GetById(id, partitionKey, CancellationToken.None); } /// public TDocument GetById(TKey id, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbReader.GetById(id, partitionKey, cancellationToken); } /// public async Task GetOneAsync(Expression> filter) where TDocument : IDocument { return await GetOneAsync(filter, null, CancellationToken.None); } /// public async Task GetOneAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return await GetOneAsync(filter, null, cancellationToken); } /// public async Task GetOneAsync(Expression> filter, string partitionKey) where TDocument : IDocument { return await GetOneAsync(filter, partitionKey, CancellationToken.None); } /// public async Task GetOneAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.GetOneAsync(filter, partitionKey, cancellationToken); } /// public TDocument GetOne(Expression> filter) where TDocument : IDocument { return GetOne(filter, null, CancellationToken.None); } /// public TDocument GetOne(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return GetOne(filter, null, cancellationToken); } /// public TDocument GetOne(Expression> filter, string partitionKey) where TDocument : IDocument { return GetOne(filter, partitionKey, CancellationToken.None); } /// public TDocument GetOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbReader.GetOne(filter, partitionKey, cancellationToken); } /// public IFindFluent GetCursor(Expression> filter, string partitionKey = null) where TDocument : IDocument { return MongoDbReader.GetCursor(filter, partitionKey); } /// public async Task AnyAsync(Expression> filter) where TDocument : IDocument { return await AnyAsync(filter, null, CancellationToken.None); } /// public async Task AnyAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return await AnyAsync(filter, null, cancellationToken); } /// public async Task AnyAsync(Expression> filter, string partitionKey) where TDocument : IDocument { return await AnyAsync(filter, partitionKey, CancellationToken.None); } /// public async Task AnyAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.AnyAsync(filter, partitionKey, cancellationToken); } /// public bool Any(Expression> filter) where TDocument : IDocument { return Any(filter, null, CancellationToken.None); } /// public bool Any(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return Any(filter, null, cancellationToken); } /// public bool Any(Expression> filter, string partitionKey) where TDocument : IDocument { return Any(filter, partitionKey, CancellationToken.None); } /// public bool Any(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbReader.Any(filter, partitionKey, cancellationToken); } /// public async Task> GetAllAsync(Expression> filter) where TDocument : IDocument { return await GetAllAsync(filter, null, CancellationToken.None); } /// public async Task> GetAllAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return await GetAllAsync(filter, null, cancellationToken); } /// public async Task> GetAllAsync(Expression> filter, string partitionKey) where TDocument : IDocument { return await GetAllAsync(filter, partitionKey, CancellationToken.None); } /// public async Task> GetAllAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.GetAllAsync(filter, partitionKey, cancellationToken); } /// public List GetAll(Expression> filter) where TDocument : IDocument { return GetAll(filter, null, CancellationToken.None); } /// public List GetAll(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return GetAll(filter, null, cancellationToken); } /// public List GetAll(Expression> filter, string partitionKey) where TDocument : IDocument { return GetAll(filter, partitionKey, CancellationToken.None); } /// public List GetAll(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbReader.GetAll(filter, partitionKey, cancellationToken); } /// public async Task CountAsync(Expression> filter) where TDocument : IDocument { return await CountAsync(filter, null, CancellationToken.None); } /// public async Task CountAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return await CountAsync(filter, null, cancellationToken); } /// public async Task CountAsync(Expression> filter, string partitionKey) where TDocument : IDocument { return await CountAsync(filter, partitionKey, CancellationToken.None); } /// public async Task CountAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.CountAsync(filter, partitionKey, cancellationToken); } /// public long Count(Expression> filter) where TDocument : IDocument { return Count(filter, null, CancellationToken.None); } /// public long Count(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument { return Count(filter, null, cancellationToken); } /// public long Count(Expression> filter, string partitionKey) where TDocument : IDocument { return Count(filter, partitionKey, CancellationToken.None); } /// public long Count(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbReader.Count(filter, partitionKey, cancellationToken); } /// public async Task GetByMaxAsync(Expression> filter, Expression> maxValueSelector) where TDocument : IDocument { return await GetByMaxAsync(filter, maxValueSelector, null, CancellationToken.None); } /// public async Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument { return await GetByMaxAsync(filter, maxValueSelector, null, cancellationToken); } /// public async Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument { return await GetByMaxAsync(filter, maxValueSelector, partitionKey, CancellationToken.None); } /// public async Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.GetByMaxAsync(filter, maxValueSelector, partitionKey, cancellationToken); } /// public TDocument GetByMax(Expression> filter, Expression> maxValueSelector) where TDocument : IDocument { return GetByMax(filter, maxValueSelector, null, CancellationToken.None); } /// public TDocument GetByMax( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument { return GetByMax(filter, maxValueSelector, null, cancellationToken); } /// public TDocument GetByMax( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument { return GetByMax(filter, maxValueSelector, partitionKey, CancellationToken.None); } /// public TDocument GetByMax( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbReader.GetByMax(filter, maxValueSelector, partitionKey, cancellationToken); } /// public async Task GetByMinAsync(Expression> filter, Expression> minValueSelector) where TDocument : IDocument { return await GetByMinAsync(filter, minValueSelector, null, CancellationToken.None); } /// public async Task GetByMinAsync( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument { return await GetByMinAsync(filter, minValueSelector, null, cancellationToken); } /// public async Task GetByMinAsync( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument { return await GetByMinAsync(filter, minValueSelector, partitionKey, CancellationToken.None); } /// public async Task GetByMinAsync( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.GetByMinAsync(filter, minValueSelector, partitionKey, cancellationToken); } /// public TDocument GetByMin(Expression> filter, Expression> minValueSelector) where TDocument : IDocument { return GetByMin(filter, minValueSelector, null, CancellationToken.None); } /// public TDocument GetByMin( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument { return GetByMin(filter, minValueSelector, null, cancellationToken); } /// public TDocument GetByMin( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument { return GetByMin(filter, minValueSelector, partitionKey, CancellationToken.None); } /// public TDocument GetByMin( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbReader.GetByMin(filter, minValueSelector, partitionKey, cancellationToken); } /// public async Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector) where TDocument : IDocument { return await GetMaxValueAsync(filter, maxValueSelector, null, CancellationToken.None); } /// public async Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument { return await GetMaxValueAsync(filter, maxValueSelector, null, cancellationToken); } /// public async Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument { return await GetMaxValueAsync(filter, maxValueSelector, partitionKey, CancellationToken.None); } /// public async Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.GetMaxValueAsync(filter, maxValueSelector, partitionKey, cancellationToken); } /// public TValue GetMaxValue(Expression> filter, Expression> maxValueSelector) where TDocument : IDocument { return GetMaxValue(filter, maxValueSelector, null, CancellationToken.None); } /// public TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument { return GetMaxValue(filter, maxValueSelector, null, cancellationToken); } /// public TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument { return GetMaxValue(filter, maxValueSelector, partitionKey, CancellationToken.None); } /// public TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbReader.GetMaxValue(filter, maxValueSelector, partitionKey, cancellationToken); } /// public virtual async Task GetMinValueAsync( Expression> filter, Expression> minValueSelector) where TDocument : IDocument { return await GetMinValueAsync(filter, minValueSelector, null, CancellationToken.None); } /// public virtual async Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument { return await GetMinValueAsync(filter, minValueSelector, null, cancellationToken); } /// public virtual async Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument { return await GetMinValueAsync(filter, minValueSelector, partitionKey, CancellationToken.None); } /// public virtual async Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.GetMinValueAsync(filter, minValueSelector, partitionKey, cancellationToken); } /// public virtual TValue GetMinValue(Expression> filter, Expression> minValueSelector) where TDocument : IDocument { return GetMinValue(filter, minValueSelector, null, CancellationToken.None); } /// public virtual TValue GetMinValue( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument { return GetMinValue(filter, minValueSelector, null, cancellationToken); } /// public virtual TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument { return GetMinValue(filter, minValueSelector, partitionKey, CancellationToken.None); } /// public virtual TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbReader.GetMinValue(filter, minValueSelector, partitionKey, cancellationToken); } #endregion #region Maths /// public virtual async Task SumByAsync(Expression> filter, Expression> selector) where TDocument : IDocument { return await SumByAsync(filter, selector, null, CancellationToken.None); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, CancellationToken cancellationToken) where TDocument : IDocument { return await SumByAsync(filter, selector, null, cancellationToken); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey) where TDocument : IDocument { return await SumByAsync(filter, selector, partitionKey, CancellationToken.None); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.SumByAsync(filter, selector, partitionKey, cancellationToken); } /// public virtual async Task SumByAsync(Expression> filter, Expression> selector) where TDocument : IDocument { return await SumByAsync(filter, selector, null, CancellationToken.None); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, CancellationToken cancellationToken) where TDocument : IDocument { return await SumByAsync(filter, selector, null, cancellationToken); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey) where TDocument : IDocument { return await SumByAsync(filter, selector, partitionKey, CancellationToken.None); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbReader.SumByAsync(filter, selector, partitionKey, cancellationToken); } /// public virtual int SumBy(Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument { return MongoDbReader.SumBy(filter, selector, partitionKey); } /// public virtual decimal SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument { return MongoDbReader.SumBy(filter, selector, partitionKey); } #endregion Maths #region Project /// public virtual async Task ProjectOneAsync( Expression> filter, Expression> projection) where TDocument : IDocument where TProjection : class { return await ProjectOneAsync(filter, projection, null, CancellationToken.None); } /// public virtual async Task ProjectOneAsync( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class { return await ProjectOneAsync(filter, projection, null, cancellationToken); } /// public virtual async Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TProjection : class { return await ProjectOneAsync(filter, projection, partitionKey, CancellationToken.None); } /// public virtual async Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class { return await MongoDbReader.ProjectOneAsync(filter, projection, partitionKey, cancellationToken); } /// public virtual TProjection ProjectOne( Expression> filter, Expression> projection) where TDocument : IDocument where TProjection : class { return ProjectOne(filter, projection, null, CancellationToken.None); } /// public virtual TProjection ProjectOne( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class { return ProjectOne(filter, projection, null, cancellationToken); } /// public virtual TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TProjection : class { return ProjectOne(filter, projection, partitionKey, CancellationToken.None); } /// public virtual TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class { return MongoDbReader.ProjectOne(filter, projection, partitionKey, cancellationToken); } /// public virtual async Task> ProjectManyAsync( Expression> filter, Expression> projection) where TDocument : IDocument where TProjection : class { return await ProjectManyAsync(filter, projection, null, CancellationToken.None); } /// public virtual async Task> ProjectManyAsync( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class { return await ProjectManyAsync(filter, projection, null, cancellationToken); } /// public virtual async Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TProjection : class { return await ProjectManyAsync(filter, projection, partitionKey, CancellationToken.None); } /// public virtual async Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class { return await MongoDbReader.ProjectManyAsync(filter, projection, partitionKey, cancellationToken); } /// public virtual List ProjectMany( Expression> filter, Expression> projection) where TDocument : IDocument where TProjection : class { return ProjectMany(filter, projection, null, CancellationToken.None); } /// public virtual List ProjectMany( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class { return ProjectMany(filter, projection, null, cancellationToken); } /// public virtual List ProjectMany( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TProjection : class { return ProjectMany(filter, projection, partitionKey, CancellationToken.None); } /// public virtual List ProjectMany( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TProjection : class { return MongoDbReader.ProjectMany(filter, projection, partitionKey, cancellationToken); } #endregion Project } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/BaseMongoRepository.TKey.Update.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.DataAccess.Update; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { public abstract partial class BaseMongoRepository : IBaseMongoRepository_Update where TKey : IEquatable { private IMongoDbUpdater _mongoDbUpdater; /// /// The MongoDb accessor to update data. /// protected virtual IMongoDbUpdater MongoDbUpdater { get { if (_mongoDbUpdater != null) { return _mongoDbUpdater; } lock (_initLock) { if (_mongoDbUpdater == null) { _mongoDbUpdater = new MongoDbUpdater(MongoDbContext); } } return _mongoDbUpdater; } set => _mongoDbUpdater = value; } /// public virtual async Task UpdateOneAsync(TDocument modifiedDocument) where TDocument : IDocument { return await UpdateOneAsync(modifiedDocument, CancellationToken.None); } /// public virtual async Task UpdateOneAsync(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(modifiedDocument, cancellationToken); } /// public virtual bool UpdateOne(TDocument modifiedDocument) where TDocument : IDocument { return UpdateOne(modifiedDocument, CancellationToken.None); } /// public virtual bool UpdateOne(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(modifiedDocument, cancellationToken); } /// public virtual async Task UpdateOneAsync(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument { return await UpdateOneAsync(documentToModify, update, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(documentToModify, update, cancellationToken); } /// public virtual bool UpdateOne(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument { return UpdateOne(documentToModify, update, CancellationToken.None); } /// public virtual bool UpdateOne(TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(documentToModify, update, cancellationToken); } /// public virtual bool UpdateOne(TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument { return UpdateOne(documentToModify, field, value, CancellationToken.None); } /// public virtual bool UpdateOne( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(documentToModify, field, value, cancellationToken); } /// public virtual async Task UpdateOneAsync(TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument { return await UpdateOneAsync(documentToModify, field, value, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(documentToModify, field, value, cancellationToken); } /// public virtual bool UpdateOne(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument { return UpdateOne(filter, field, value, null, CancellationToken.None); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateOne(filter, field, value, null, cancellationToken); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return UpdateOne(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(filter, field, value, partitionKey, cancellationToken); } /// public virtual bool UpdateOne(Expression> filter, Expression> field, TField value) where TDocument : IDocument { return UpdateOne(filter, field, value, null, CancellationToken.None); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateOne(filter, field, value, null, cancellationToken); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return UpdateOne(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateOne(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return await UpdateOneAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateOneAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateManyAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return await UpdateManyAsync(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateManyAsync(filter, field, value, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateManyAsync(filter, updateDefinition, partitionKey, cancellationToken); } /// public virtual async Task UpdateManyAsync(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, null, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, null, cancellationToken); } /// public virtual async Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument { return await UpdateManyAsync(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual async Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return await MongoDbUpdater.UpdateManyAsync(filter, updateDefinition, partitionKey, cancellationToken); } /// public virtual long UpdateMany(Expression> filter, Expression> field, TField value) where TDocument : IDocument { return UpdateMany(filter, field, value, null, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateMany(filter, field, value, null, cancellationToken); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return UpdateMany(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, field, value, partitionKey, cancellationToken); } /// public virtual long UpdateMany(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, field, value, null, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, field, value, null, cancellationToken); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, field, value, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, field, value, partitionKey, cancellationToken); } /// public virtual long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, null, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, null, cancellationToken); } /// public virtual long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, updateDefinition, partitionKey, cancellationToken); } /// public virtual long UpdateMany(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, null, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, null, cancellationToken); } /// public virtual long UpdateMany(Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument { return UpdateMany(filter, updateDefinition, partitionKey, CancellationToken.None); } /// public virtual long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument { return MongoDbUpdater.UpdateMany(filter, updateDefinition, partitionKey, cancellationToken); } } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/IBaseMongoRepository.TKey.Create.cs ================================================ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The interface exposing data insertion functionality for Key typed repositories. /// /// public interface IBaseMongoRepository_Create where TKey : IEquatable { /// /// Asynchronously adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The document you want to add. Task AddOneAsync(TDocument document) where TDocument : IDocument; /// /// Asynchronously adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The document you want to add. /// The cancellation Token. Task AddOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The document you want to add. void AddOne(TDocument document) where TDocument : IDocument; /// /// Adds a document to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The document you want to add. /// The cancellation token. void AddOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The documents you want to add. Task AddManyAsync(IEnumerable documents) where TDocument : IDocument; /// /// Asynchronously adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The documents you want to add. /// An optional cancellation Token. Task AddManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The documents you want to add. void AddMany(IEnumerable documents) where TDocument : IDocument; /// /// Adds a list of documents to the collection. /// Populates the Id and AddedAtUtc fields if necessary. /// /// The type representing a Document. /// The documents you want to add. /// The cancellation token. void AddMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument; } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/IBaseMongoRepository.TKey.Delete.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The interface exposing deletion functionality for Key typed repositories. /// /// The type of the document Id. public interface IBaseMongoRepository_Delete where TKey : IEquatable { /// /// Deletes a document. /// /// The type representing a Document. /// The document you want to delete. /// The number of documents deleted. long DeleteOne(TDocument document) where TDocument : IDocument; /// /// Deletes a document. /// /// The type representing a Document. /// The document you want to delete. /// The cancellation token. /// The number of documents deleted. long DeleteOne(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The number of documents deleted. long DeleteOne(Expression> filter) where TDocument : IDocument; /// /// Deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token. /// The number of documents deleted. long DeleteOne(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The number of documents deleted. long DeleteOne(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. /// The number of documents deleted. long DeleteOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The document you want to delete. /// The number of documents deleted. Task DeleteOneAsync(TDocument document) where TDocument : IDocument; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// The document you want to delete. /// The cancellation token. /// The number of documents deleted. Task DeleteOneAsync(TDocument document, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The number of documents deleted. Task DeleteOneAsync(Expression> filter) where TDocument : IDocument; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token. /// The number of documents deleted. Task DeleteOneAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The number of documents deleted. Task DeleteOneAsync(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Asynchronously deletes a document matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. /// The number of documents deleted. Task DeleteOneAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The number of documents deleted. Task DeleteManyAsync(Expression> filter) where TDocument : IDocument; /// /// Asynchronously deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token. /// The number of documents deleted. Task DeleteManyAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The number of documents deleted. Task DeleteManyAsync(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Asynchronously deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The cancellation token. /// The number of documents deleted. Task DeleteManyAsync(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Asynchronously deletes a list of documents. /// /// The type representing a Document. /// The list of documents to delete. /// The number of documents deleted. Task DeleteManyAsync(IEnumerable documents) where TDocument : IDocument; /// /// Asynchronously deletes a list of documents. /// /// The type representing a Document. /// The list of documents to delete. /// The cancellation token. /// The number of documents deleted. Task DeleteManyAsync(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Deletes a list of documents. /// /// The type representing a Document. /// The list of documents to delete. /// The number of documents deleted. long DeleteMany(IEnumerable documents) where TDocument : IDocument; /// /// Deletes a list of documents. /// /// The type representing a Document. /// The list of documents to delete. /// The cancellation token. /// The number of documents deleted. long DeleteMany(IEnumerable documents, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The number of documents deleted. long DeleteMany(Expression> filter) where TDocument : IDocument; /// /// Deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// The cancellation token /// The number of documents deleted. long DeleteMany(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// The number of documents deleted. long DeleteMany(Expression> filter, string partitionKey) where TDocument : IDocument; /// /// Deletes the documents matching the condition of the LINQ expression filter. /// /// The type representing a Document. /// A LINQ expression filter. /// An optional partition key. /// /// The number of documents deleted. long DeleteMany(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/IBaseMongoRepository.TKey.Index.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The interface exposing index management functionality for Key typed repositories. /// /// public interface IBaseMongoRepository_Index where TKey : IEquatable { /// /// Returns the names of the indexes present on a collection. /// /// The type representing a Document. /// A list containing the names of the indexes on on the concerned collection. Task> GetIndexesNamesAsync() where TDocument : IDocument; /// /// Returns the names of the indexes present on a collection. /// /// The type representing a Document. /// The cancellation token. /// A list containing the names of the indexes on on the concerned collection. Task> GetIndexesNamesAsync(CancellationToken cancellationToken) where TDocument : IDocument; /// /// Returns the names of the indexes present on a collection. /// /// The type representing a Document. /// An optional partition key /// A list containing the names of the indexes on on the concerned collection. Task> GetIndexesNamesAsync(string partitionKey) where TDocument : IDocument; /// /// Returns the names of the indexes present on a collection. /// /// The type representing a Document. /// An optional partition key /// The cancellation token /// A list containing the names of the indexes on on the concerned collection. Task> GetIndexesNamesAsync(string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field) where TDocument : IDocument; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// The cancellation token. /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// The cancellation token. /// The result of the create index operation. Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// An optional partition key. /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateTextIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument; /// /// Create a text index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateTextIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// The result of the create index operation. Task CreateAscendingIndexAsync(Expression> field) where TDocument : IDocument; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// The cancellation token. /// The result of the create index operation. Task CreateAscendingIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateAscendingIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// The cancellation token. /// The result of the create index operation. Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// An optional partition key. /// The result of the create index operation. Task CreateAscendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateAscendingIndexAsync(Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument; /// /// Creates an index on the given field in ascending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateAscendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// The result of the create index operation. Task CreateDescendingIndexAsync(Expression> field) where TDocument : IDocument; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// The cancellation token. /// The result of the create index operation. Task CreateDescendingIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateDescendingIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// The cancellation token. /// The result of the create index operation. Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// An optional partition key. /// The result of the create index operation. Task CreateDescendingIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateDescendingIndexAsync(Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument; /// /// Creates an index on the given field in descending order. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateDescendingIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// The result of the create index operation. Task CreateHashedIndexAsync(Expression> field) where TDocument : IDocument; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// The cancellation token. /// The result of the create index operation. Task CreateHashedIndexAsync(Expression> field, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateHashedIndexAsync(Expression> field, IndexCreationOptions indexCreationOptions) where TDocument : IDocument; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// The cancellation token. /// The result of the create index operation. Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// An optional partition key. /// The result of the create index operation. Task CreateHashedIndexAsync(Expression> field, string partitionKey) where TDocument : IDocument; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateHashedIndexAsync(Expression> field, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument; /// /// Creates a hashed index on the given field. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The field we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateHashedIndexAsync( Expression> field, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The fields we want to index. /// The result of the create index operation. Task CreateCombinedTextIndexAsync(IEnumerable>> fields) where TDocument : IDocument; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The fields we want to index. /// The cancellation token. /// The result of the create index operation. Task CreateCombinedTextIndexAsync(IEnumerable>> fields, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The fields we want to index. /// Options for creating an index. /// The result of the create index operation. Task CreateCombinedTextIndexAsync(IEnumerable>> fields, IndexCreationOptions indexCreationOptions) where TDocument : IDocument; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The fields we want to index. /// Options for creating an index. /// The cancellation token. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The fields we want to index. /// An optional partition key. /// The result of the create index operation. Task CreateCombinedTextIndexAsync(IEnumerable>> fields, string partitionKey) where TDocument : IDocument; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The fields we want to index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The fields we want to index. /// Options for creating an index. /// An optional partition key. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey) where TDocument : IDocument; /// /// Creates a combined text index. /// IndexCreationOptions can be supplied to further specify /// how the creation should be done. /// /// The type representing a Document. /// The fields we want to index. /// Options for creating an index. /// An optional partition key. /// The cancellation token. /// The result of the create index operation. Task CreateCombinedTextIndexAsync( IEnumerable>> fields, IndexCreationOptions indexCreationOptions, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Drops the index given a field name /// /// The type representing a Document. /// The name of the index Task DropIndexAsync(string indexName) where TDocument : IDocument; /// /// Drops the index given a field name /// /// The type representing a Document. /// The name of the index /// The cancellation token. Task DropIndexAsync(string indexName, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Drops the index given a field name /// /// The type representing a Document. /// The name of the index /// An optional partition key Task DropIndexAsync(string indexName, string partitionKey) where TDocument : IDocument; /// /// Drops the index given a field name /// /// The type representing a Document. /// The name of the index /// An optional partition key /// The cancellation token. Task DropIndexAsync(string indexName, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/IBaseMongoRepository.TKey.Update.cs ================================================ using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Mongo Repository Update interface. used to update documents in the collections. /// /// public interface IBaseMongoRepository_Update where TKey : IEquatable { /// /// Asynchronously Updates a document. /// /// The type representing a Document. /// The document with the modifications you want to persist. Task UpdateOneAsync(TDocument modifiedDocument) where TDocument : IDocument; /// /// Asynchronously Updates a document. /// /// The type representing a Document. /// The document with the modifications you want to persist. /// The cancellation token. Task UpdateOneAsync(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Updates a document. /// /// The type representing a Document. /// The document with the modifications you want to persist. bool UpdateOne(TDocument modifiedDocument) where TDocument : IDocument; /// /// Updates a document. /// /// The type representing a Document. /// The document with the modifications you want to persist. /// The cancellation token. bool UpdateOne(TDocument modifiedDocument, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document you want to modify. /// The update definition for the document. Task UpdateOneAsync(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document you want to modify. /// The update definition for the document. /// The cancellation token. Task UpdateOneAsync(TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document you want to modify. /// The update definition for the document. bool UpdateOne(TDocument documentToModify, UpdateDefinition update) where TDocument : IDocument; /// /// Takes a document you want to modify and applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document you want to modify. /// The update definition for the document. /// The cancellation token. bool UpdateOne(TDocument documentToModify, UpdateDefinition update, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. bool UpdateOne(TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. /// The cancellation token. bool UpdateOne( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. Task UpdateOneAsync(TDocument documentToModify, Expression> field, TField value) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document you want to modify. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateOneAsync( TDocument documentToModify, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. bool UpdateOne(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. bool UpdateOne( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The cancellation token. bool UpdateOne( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. bool UpdateOne( Expression> filter, Expression> field, TField value) where TDocument : IDocument; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. bool UpdateOne( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The cancellation token. bool UpdateOne( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. Task UpdateOneAsync(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument; /// /// Updates the property field with the given value update a property field in entities. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The cancellation token. Task UpdateOneAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. Task UpdateOneAsync(Expression> filter, Expression> field, TField value) where TDocument : IDocument; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateOneAsync( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument; /// /// For the entity selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The cancellation token. Task UpdateOneAsync( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. Task UpdateManyAsync(Expression> filter, Expression> field, TField value) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateManyAsync( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The cancellation token. Task UpdateManyAsync( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. Task UpdateManyAsync(FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The cancellation token. Task UpdateManyAsync( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The cancellation token. Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. /// The cancellation token. Task UpdateManyAsync( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. Task UpdateManyAsync(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The cancellation token. Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. Task UpdateManyAsync(Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. /// The cancellation token. Task UpdateManyAsync( Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. long UpdateMany( Expression> filter, Expression> field, TField value) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. long UpdateMany( Expression> filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The partition key for the document. /// The cancellation token. long UpdateMany( Expression> filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. long UpdateMany( FilterDefinition filter, Expression> field, TField value) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The cancellation token. long UpdateMany( FilterDefinition filter, Expression> field, TField value, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey) where TDocument : IDocument; /// /// For the entities selected by the filter, updates the property field with the given value. /// /// The type representing a Document. /// The type of the field. /// The document filter. /// The field selector. /// The new value of the property field. /// The value of the partition key. /// The cancellation token. long UpdateMany( FilterDefinition filter, Expression> field, TField value, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The cancellation token. long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. long UpdateMany(FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. /// The cancellation token. long UpdateMany( FilterDefinition filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. long UpdateMany(Expression> filter, UpdateDefinition updateDefinition) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The cancellation token. long UpdateMany(Expression> filter, UpdateDefinition updateDefinition, CancellationToken cancellationToken) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. long UpdateMany(Expression> filter, UpdateDefinition updateDefinition, string partitionKey) where TDocument : IDocument; /// /// For the entities selected by the filter, applies the update you have defined in MongoDb. /// /// The type representing a Document. /// The document filter. /// The update definition to apply. /// The value of the partition key. /// The cancellation token. long UpdateMany( Expression> filter, UpdateDefinition updateDefinition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument; } } ================================================ FILE: MongoDbGenericRepository/KeyTypedRepository/IBaseMongoRepository.TKey.cs ================================================ using System; namespace MongoDbGenericRepository { /// /// The interface exposing all the CRUD and Index functionalities for Key typed repositories. /// /// The type of the document Id. public interface IBaseMongoRepository : IReadOnlyMongoRepository, IBaseMongoRepository_Create, IBaseMongoRepository_Delete, IBaseMongoRepository_Index, IBaseMongoRepository_Update where TKey : IEquatable { } } ================================================ FILE: MongoDbGenericRepository/Models/Document.cs ================================================ using MongoDB.Bson.Serialization.Attributes; using System; namespace MongoDbGenericRepository.Models { /// /// This class represents a basic document that can be stored in MongoDb. /// Your document must implement this class in order for the MongoDbRepository to handle them. /// public class Document : IDocument { /// /// The document constructor /// public Document() { Id = Guid.NewGuid(); AddedAtUtc = DateTime.UtcNow; } /// /// The Id of the document /// [BsonId] public Guid Id { get; set; } /// /// The datetime in UTC at which the document was added. /// public DateTime AddedAtUtc { get; set; } /// /// The version of the schema of the document /// public int Version { get; set; } } } ================================================ FILE: MongoDbGenericRepository/Models/IDocument.cs ================================================ using System; namespace MongoDbGenericRepository.Models { /// /// This class represents a basic document that can be stored in MongoDb. /// Your document must implement this class in order for the MongoDbRepository to handle them. /// public interface IDocument where TKey : IEquatable { /// /// The Primary Key, which must be decorated with the [BsonId] attribute /// if you want the MongoDb C# driver to consider it to be the document ID. /// TKey Id { get; set; } /// /// A version number, to indicate the version of the schema. /// int Version { get; set; } } /// /// This class represents a basic document that can be stored in MongoDb. /// Your document must implement this class in order for the MongoDbRepository to handle them. /// public interface IDocument : IDocument { } } ================================================ FILE: MongoDbGenericRepository/Models/IPartitionedDocument.cs ================================================ namespace MongoDbGenericRepository.Models { /// /// This class represents a document that can be inserted in a collection that can be partitioned. /// The partition key allows for the creation of different collections having the same document schema. /// This can be useful if you are planning to build a Software as a Service (SaaS) Platform, or if you want to reduce indexing. /// You could for example insert Logs in different collections based on the week and year they where created, or their Log category/source. /// public interface IPartitionedDocument { /// /// The partition key used to partition your collection. /// string PartitionKey { get; set; } } } ================================================ FILE: MongoDbGenericRepository/Models/IndexCreationOptions.cs ================================================ using System; namespace MongoDbGenericRepository.Models { /// /// Options for creating an index. /// public class IndexCreationOptions { /// /// Gets or sets a value indicating whether the index is a unique index. /// public bool? Unique { get; set; } /// /// Gets or sets the index version for text indexes. /// public int? TextIndexVersion { get; set; } /// /// Gets or sets the index version for 2dsphere indexes. /// public int? SphereIndexVersion { get; set; } /// /// Gets or sets a value indicating whether the index is a sparse index. /// public bool? Sparse { get; set; } /// /// Gets or sets the index name. /// public string Name { get; set; } /// /// Gets or sets the min value for 2d indexes. /// public double? Min { get; set; } /// /// Gets or sets the max value for 2d indexes. /// public double? Max { get; set; } /// /// Gets or sets the language override. /// public string LanguageOverride { get; set; } /// /// Gets or sets when documents expire (used with TTL indexes). /// public TimeSpan? ExpireAfter { get; set; } /// /// Gets or sets the default language. /// public string DefaultLanguage { get; set; } /// /// Gets or sets the precision, in bits, used with geohash indexes. /// public int? Bits { get; set; } /// /// Gets or sets a value indicating whether to create the index in the background. /// public bool? Background { get; set; } /// /// Gets or sets the version of the index. /// public int? Version { get; set; } } } ================================================ FILE: MongoDbGenericRepository/Models/PartitionedDocument.cs ================================================ namespace MongoDbGenericRepository.Models { /// /// This class represents a document that can be inserted in a collection that can be partitioned. /// The partition key allows for the creation of different collections having the same document schema. /// This can be useful if you are planning to build a Software as a Service (SaaS) Platform, or if you want to reduce indexing. /// You could for example insert Logs in different collections based on the week and year they where created, or their Log category/source. /// public class PartitionedDocument : Document, IPartitionedDocument { /// /// The constructor, it needs a partition key. /// /// public PartitionedDocument(string partitionKey) { PartitionKey = partitionKey; } /// /// The name of the property used for partitioning the collection /// This will not be inserted into the collection. /// This partition key will be prepended to the collection name to create a new collection. /// public string PartitionKey { get; set; } } } ================================================ FILE: MongoDbGenericRepository/MongoDbContext.cs ================================================ using MongoDB.Driver; using MongoDbGenericRepository.Attributes; using MongoDbGenericRepository.Utils; using System.Linq; using System.Reflection; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; using MongoDbGenericRepository.Internals; namespace MongoDbGenericRepository { /// /// The MongoDb context /// public class MongoDbContext : IMongoDbContext { /// /// The IMongoClient from the official MongoDB driver /// public IMongoClient Client { get; } /// /// The IMongoDatabase from the official MongoDB driver /// public IMongoDatabase Database { get; } /// /// The constructor of the MongoDbContext, it needs an object implementing . /// /// An object implementing IMongoDatabase public MongoDbContext(IMongoDatabase mongoDatabase) { // Avoid legacy UUID representation: use Binary 0x04 subtype. InitializeGuidRepresentation(); Database = mongoDatabase; Client = Database.Client; } /// /// The constructor of the MongoDbContext, it needs a connection string and a database name. /// /// The connections string. /// The name of your database. public MongoDbContext(string connectionString, string databaseName) { InitializeGuidRepresentation(); Client = new MongoClient(connectionString); Database = Client.GetDatabase(databaseName); } /// /// Initialise an instance of a using a connection string /// /// public MongoDbContext(string connectionString) : this(connectionString, new MongoUrl(connectionString).DatabaseName) { } /// /// The constructor of the MongoDbContext, it needs a connection string and a database name. /// /// The MongoClient. /// The name of your database. public MongoDbContext(MongoClient client, string databaseName) { InitializeGuidRepresentation(); Client = client; Database = client.GetDatabase(databaseName); } /// /// Returns a collection for a document type. Also handles document types with a partition key. /// /// The type representing a Document. /// The optional value of the partition key. public virtual IMongoCollection GetCollection(string partitionKey = null) { return Database.GetCollection(GetCollectionName(partitionKey)); } /// /// Drops a collection, use very carefully. /// /// The type representing a Document. public virtual void DropCollection(string partitionKey = null) { Database.DropCollection(GetCollectionName(partitionKey)); } /// /// Sets the Guid representation of the MongoDB Driver. /// /// The new value of the GuidRepresentation public virtual void SetGuidRepresentation(GuidRepresentation guidRepresentation) { // GuidRepresentation and GuidRepresentationMode will be removed in the next major release of the MongoDB Driver. // We can safely replace this with RepositorySerializationProvider.Instance.RegisterSerializer once we upgrade to the next major release. #pragma warning disable CS0618 #if NETSTANDARD2_0 || NET472 BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3; #endif RepositorySerializationProvider.Instance.RegisterSerializer(new GuidSerializer(guidRepresentation)); #pragma warning restore CS0618 } /// /// Extracts the CollectionName attribute from the entity type, if any. /// /// The type representing a Document. /// The name of the collection in which the TDocument is stored. protected virtual string GetAttributeCollectionName() { return (typeof(TDocument).GetTypeInfo() .GetCustomAttributes(typeof(CollectionNameAttribute)) .FirstOrDefault() as CollectionNameAttribute)?.Name; } /// /// Initialize the Guid representation of the MongoDB Driver. /// Override this method to change the default GuidRepresentation. /// protected virtual void InitializeGuidRepresentation() { // by default, avoid legacy UUID representation: use Binary 0x04 subtype. SetGuidRepresentation(GuidRepresentation.Standard); } /// /// Given the document type and the partition key, returns the name of the collection it belongs to. /// /// The type representing a Document. /// The value of the partition key. /// The name of the collection. protected virtual string GetCollectionName(string partitionKey) { var collectionName = GetAttributeCollectionName() ?? Pluralize(); if (string.IsNullOrEmpty(partitionKey)) { return collectionName; } return $"{partitionKey}-{collectionName}"; } /// /// Very naively pluralizes a TDocument type name. /// /// The type representing a Document. /// The pluralized document name. protected virtual string Pluralize() { return (typeof(TDocument).Name.Pluralize()).Camelize(); } } } ================================================ FILE: MongoDbGenericRepository/MongoDbGenericRepository.csproj ================================================  net472;netstandard2.0;netstandard2.1 disable enable 12.0 true MongoDbGenericRepository Alexandre Spieser MongoDb Generic Repository A generic repository implementation using the MongoDB C# 2.x driver. MIT https://github.com/alexandre-spieser/mongodb-generic-repository false https://github.com/alexandre-spieser/mongodb-generic-repository/releases Copyright 2024 (c) Alexandre Spieser. All rights reserved. MongoDb Repository Generic NoSql true 2.0.0 https://github.com/alexandre-spieser/mongodb-generic-repository Git README.md bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml ================================================ FILE: MongoDbGenericRepository/MongoDbGenericRepository.xml ================================================ MongoDbGenericRepository The IBaseMongoRepository interface exposes the CRUD functionality of the BaseMongoRepository. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. GetAndUpdateOne with filter The type representing a Document. GetAndUpdateOne with filter The type representing a Document. The type of the primary key for a Document. Asynchronously Updates a document. The type representing a Document. The type of the primary key for a Document. The document with the modifications you want to persist. Updates a document. The type representing a Document. The type of the primary key for a Document. The document with the modifications you want to persist. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document you want to modify. The update definition for the document. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document you want to modify. The update definition for the document. For the entity selected by the filter, updates the property field with the given value.. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document filter. The update definition to apply. The value of the partition key. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document with the modifications you want to persist. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document with the modifications you want to persist. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document to modify. The update definition. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document to modify. The update definition. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The document to modify. The field to update. The value of the field. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The document to modify. The field to update. The value of the field. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document with the modifications you want to persist. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document with the modifications you want to persist. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document to modify. The update definition. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document to modify. The update definition. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The document to modify. The field to update. The value of the field. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The document to modify. The field to update. The value of the field. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Asynchronously Updates a document. The type representing a Document. The type of the primary key for a Document. The document with the modifications you want to persist. Updates a document. The type representing a Document. The type of the primary key for a Document. The document with the modifications you want to persist. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document you want to modify. The update definition for the document. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document you want to modify. The update definition for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. Updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, apply the update definition. The type representing a Document. The type of the primary key for a Document. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, apply the update definition. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The update definition. The value of the partition key. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, apply the update definition. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The update definition. The value of the partition key. Gets a collections for a potentially partitioned document type. The document type. The type of the primary key. The document. Gets a collections for the type TDocument with a partition key. The document type. The type of the primary key. The collection partition key. Gets a collections for a potentially partitioned document type. The document type. The type of the primary key. The collection partition key. Converts a LINQ expression of TDocument, TValue to a LINQ expression of TDocument, object The document type. The type of the value. The expression to convert Maps a IndexCreationOptions object to a MongoDB.Driver.CreateIndexOptions object The options for creating an index. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by descending. An optional partition key. Asynchronously adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The document you want to add. Adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The document you want to add. Asynchronously adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The documents you want to add. Adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The documents you want to add. Sets the value of the document Id if it is not set already. The document type. The type of the primary key. The document. Deletes a document. The type representing a Document. The type of the primary key for a Document. The document you want to delete. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. The document you want to delete. The number of documents deleted. Deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a list of documents. The type representing a Document. The type of the primary key for a Document. The list of documents to delete. The number of documents deleted. Deletes a list of documents. The type representing a Document. The type of the primary key for a Document. The list of documents to delete. The number of documents deleted. Deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Returns the names of the indexes present on a collection. The type representing a Document. The type of the primary key for a Document. An optional partition key A list containing the names of the indexes on on the concerned collection. Create a text index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in ascending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in descending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a hashed index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a combined text index. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The fields we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Drops the index given a field name The type representing a Document. The type of the primary key for a Document. The name of the index An optional partition key Asynchronously returns one document given its id. The type representing a Document. The type of the primary key for a Document. The Id of the document you want to get. An optional partition key. Returns one document given its id. The type representing a Document. The type of the primary key for a Document. The Id of the document you want to get. An optional partition key. Asynchronously returns one document given an expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns one document given an expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns a collection cursor. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns true if any of the document of the collection matches the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns true if any of the document of the collection matches the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Asynchronously returns a list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns a list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Asynchronously counts how many documents match the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partitionKey Counts how many documents match the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partitionKey Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Groups a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the primary key for a Document. The type of the grouping criteria. The type of the projected group. The grouping criteria. The projected group result. The partition key of your document, if any. Groups filtered a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the primary key for a Document. The type of the grouping criteria. The type of the projected group. A LINQ expression filter. The grouping criteria. The projected group result. The partition key of your document, if any. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The property selector. Order of the sorting. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The sort definition. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Asynchronously returns a projected document matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Returns a projected document matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. The document filter. The projection expression. An optional partition key. The IBaseReadOnlyRepository exposes the generic Read Only functionality of the BaseMongoRepository. The connection string. The database name. Asynchronously returns one document given its id. The type representing a Document. The type of the primary key for a Document. The Id of the document you want to get. An optional partition key. Returns one document given its id. The type representing a Document. The type of the primary key for a Document. The Id of the document you want to get. An optional partition key. Asynchronously returns one document given an expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns one document given an expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns a collection cursor. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns true if any of the document of the collection matches the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns true if any of the document of the collection matches the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Asynchronously returns a list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns a list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Asynchronously counts how many documents match the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partitionKey Counts how many documents match the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partitionKey Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Asynchronously returns a projected document matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. The projection expression. An optional partition key. Returns a projected document matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. The projection expression. An optional partition key. Groups filtered a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the grouping criteria. The type of the projected group. The type of the primary key. The grouping criteria. The projected group result. The partition key of your document, if any. Groups filtered a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the grouping criteria. The type of the projected group. The type of the primary key. A LINQ expression filter. The grouping criteria. The projected group result. The partition key of your document, if any. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The property selector. Order of the sorting. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The sort definition. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. This is the interface of the IMongoDbContext which is managed by the . The IMongoClient from the official MongoDb driver The IMongoDatabase from the official Mongodb driver Returns a collection for a document type that has a partition key. The value of the partition key. Drops a collection having a partitionkey, use very carefully. Sets the Guid representation of the MongoDb Driver. The new value of the GuidRepresentation The IReadOnlyMongoRepository exposes the readonly functionality of the BaseMongoRepository. Asynchronously returns one document given its id. The type representing a Document. The Id of the document you want to get. An optional partition key. Returns one document given its id. The type representing a Document. The Id of the document you want to get. An optional partition key. Asynchronously returns one document given an expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. Returns one document given an expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. Returns a collection cursor. The type representing a Document. A LINQ expression filter. An optional partition key. Asynchronously returns true if any of the document of the collection matches the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Returns true if any of the document of the collection matches the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Asynchronously returns a list of the documents matching the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Returns a list of the documents matching the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Asynchronously counts how many documents match the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Counts how many documents match the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Asynchronously returns a projected document matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Returns a projected document matching the filter condition. The type representing a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Groups a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the grouping criteria. The type of the projected group. The grouping criteria. The projected group result. The partition key of your document, if any. Groups filtered a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the grouping criteria. The type of the projected group. A LINQ expression filter. The grouping criteria. The projected group result. The partition key of your document, if any. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The property selector. Order of the sorting. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The sort definition. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. This attribute allows you to specify of the name of the collection. Added at commit c117bf2a7fee378f1e02199dea9b2023a7089ee2 by https://github.com/Etchelon who has included the CollectionName attribute into the repo to give another choice to the user on how to name their collections. The attribute takes precedence of course, and if not present the library will fall back to your Pluralize method. The name of the collection in which your documents are stored. The constructor. The name of the collection. Asynchronously adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The document you want to add. Adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The document you want to add. Asynchronously adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The documents you want to add. Adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The documents you want to add. The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. Its constructor must be given a connection string and a database name. The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. Its constructor must be given a connection string and a database name. The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. Its constructor must be given a connection string and a database name. The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. Its constructor must be given a connection string and a database name. Asynchronously adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The document you want to add. Asynchronously adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The document you want to add. Adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The document you want to add. Adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The document you want to add. Asynchronously adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The documents you want to add. Asynchronously adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The documents you want to add. Adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The type of the primary key for a Document. The documents you want to add. Adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The documents you want to add. Asynchronously deletes a document. The type representing a Document. The document you want to delete. The number of documents deleted. Deletes a document. The type representing a Document. The document you want to delete. The number of documents deleted. Deletes a document matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a list of documents. The type representing a Document. The list of documents to delete. The number of documents deleted. Deletes a list of documents. The type representing a Document. The list of documents to delete. The number of documents deleted. Deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Deletes a document. The type representing a Document. The type of the primary key for a Document. The document you want to delete. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. The document you want to delete. The number of documents deleted. Deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a list of documents. The type representing a Document. The type of the primary key for a Document. The list of documents to delete. The number of documents deleted. Deletes a list of documents. The type representing a Document. The type of the primary key for a Document. The list of documents to delete. The number of documents deleted. Deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Returns the names of the indexes present on a collection. The type representing a Document. The type of the primary key for a Document. An optional partition key A list containing the names of the indexes on on the concerned collection. Returns the names of the indexes present on a collection. The type representing a Document. An optional partition key A list containing the names of the indexes on on the concerned collection. Create a text index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Create a text index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in ascending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in ascending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in descending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a hashed index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a combined text index. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The fields we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Drops the index given a field name The type representing a Document. The name of the index An optional partition key The constructor taking a connection string and a database name. The connection string of the MongoDb server. The name of the database against which you want to perform operations. The constructor taking a . A mongodb context implementing The constructor taking a . A mongodb context implementing Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. A LINQ expression filter. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. GetAndUpdateOne with filter The type representing a Document. A LINQ expression filter. GetAndUpdateOne with filter The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. Sets the value of the document Id if it is not set already. The document type. The type of the primary key. The document. Sets the value of the document Id if it is not set already. The document type. The document. Gets a collections for a potentially partitioned document type. The document type. The collection partition key. Gets a collections for the type TDocument with a partition key. The document type. The collection partition key. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document with the modifications you want to persist. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document with the modifications you want to persist. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document to modify. The update definition. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The client session. The document to modify. The update definition. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The document to modify. The field to update. The value of the field. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The document to modify. The field to update. The value of the field. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Updates a document. The type representing a Document. The type of the primary key for a Document. The type of the field to update. The client session. The filter for the update. The field to update. The value of the field. The optional partition key. The optional cancellation token. Asynchronously Updates a document. The type representing a Document. The document with the modifications you want to persist. Updates a document. The type representing a Document. The document with the modifications you want to persist. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The document you want to modify. The update definition for the document. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The document you want to modify. The update definition for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. Asynchronously Updates a document. The type representing a Document. The type of the primary key for a Document. The document with the modifications you want to persist. Updates a document. The type representing a Document. The type of the primary key for a Document. The document with the modifications you want to persist. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document you want to modify. The update definition for the document. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document you want to modify. The update definition for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the primary key for a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The type of the primary key for a Document. The document filter. The update definition to apply. The value of the partition key. Deletes a document. The type representing a Document. The type of the primary key for a Document. The document you want to delete. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. The document you want to delete. The number of documents deleted. Deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a list of documents. The type representing a Document. The type of the primary key for a Document. The list of documents to delete. The number of documents deleted. Deletes a list of documents. The type representing a Document. The type of the primary key for a Document. The list of documents to delete. The number of documents deleted. Deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Returns the names of the indexes present on a collection. The type representing a Document. The type of the primary key for a Document. An optional partition key A list containing the names of the indexes on on the concerned collection. Create a text index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in ascending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in descending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a hashed index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a combined text index. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The type of the primary key for a Document. The fields we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Drops the index given a field name The type representing a Document. The type of the primary key for a Document. The name of the index An optional partition key The interface exposing data insertion functionality for Key typed repositories. Asynchronously adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The document you want to add. Adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The document you want to add. Asynchronously adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The documents you want to add. Adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The documents you want to add. The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. Its constructor must be given a connection string and a database name. The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. Its constructor must be given a connection string and a database name. The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. Its constructor must be given a connection string and a database name. The type of the document Id. The MongoDb accessor to insert data. Asynchronously adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The document you want to add. Adds a document to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The document you want to add. Asynchronously adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The documents you want to add. Adds a list of documents to the collection. Populates the Id and AddedAtUtc fields if necessary. The type representing a Document. The documents you want to add. The MongoDb accessor to delete data. Deletes a document. The type representing a Document. The document you want to delete. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The document you want to delete. The number of documents deleted. Deletes a document matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a list of documents. The type representing a Document. The list of documents to delete. The number of documents deleted. Deletes a list of documents. The type representing a Document. The list of documents to delete. The number of documents deleted. Deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. The MongoDb accessor to manage indexes. Returns the names of the indexes present on a collection. The type representing a Document. An optional partition key A list containing the names of the indexes on on the concerned collection. Create a text index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in ascending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in descending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a hashed index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a combined text index. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The fields we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Drops the index given a field name The type representing a Document. The name of the index An optional partition key The constructor taking a connection string and a database name. The connection string of the MongoDb server. The name of the database against which you want to perform operations. The constructor taking a . A mongodb context implementing The constructor taking a . A mongodb context implementing Gets a collections for a potentially partitioned document type. The document type. The collection partition key. Gets a collections for the type TDocument with a partition key. The document type. The collection partition key. Asynchronously Updates a document. The type representing a Document. The document with the modifications you want to persist. Updates a document. The type representing a Document. The document with the modifications you want to persist. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The document you want to modify. The update definition for the document. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The document you want to modify. The update definition for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. The interface exposing deletion functionality for Key typed repositories. The type of the document Id. Deletes a document. The type representing a Document. The document you want to delete. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. The document you want to delete. The number of documents deleted. Deletes a document matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a document matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. Asynchronously deletes a list of documents. The type representing a Document. The list of documents to delete. The number of documents deleted. Deletes a list of documents. The type representing a Document. The list of documents to delete. The number of documents deleted. Deletes the documents matching the condition of the LINQ expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. The number of documents deleted. The interface exposing index management functionality for Key typed repositories. Returns the names of the indexes present on a collection. The type representing a Document. An optional partition key A list containing the names of the indexes on on the concerned collection. Create a text index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in ascending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates an index on the given field in descending order. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a hashed index on the given field. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The field we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Creates a combined text index. IndexCreationOptions can be supplied to further specify how the creation should be done. The type representing a Document. The fields we want to index. Options for creating an index. An optional partition key. The result of the create index operation. Drops the index given a field name The type representing a Document. The name of the index An optional partition key The interface exposing all the CRUD and Index functionalities for Key typed repositories. The type of the document Id. The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. Its constructor must be given a connection string and a database name. The connection string. The database name. The MongoDbContext A MongoDb Reader for read operations The constructor taking a connection string and a database name. The connection string of the MongoDb server. The name of the database against which you want to perform operations. The constructor taking a . A mongodb context implementing The constructor taking a . A mongodb context implementing Asynchronously returns one document given its id. The type representing a Document. The Id of the document you want to get. An optional partition key. Returns one document given its id. The type representing a Document. The Id of the document you want to get. An optional partition key. Asynchronously returns one document given an expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. Returns one document given an expression filter. The type representing a Document. A LINQ expression filter. An optional partition key. Returns a collection cursor. The type representing a Document. A LINQ expression filter. An optional partition key. Returns true if any of the document of the collection matches the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Returns true if any of the document of the collection matches the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Asynchronously returns a list of the documents matching the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Returns a list of the documents matching the filter condition. The type representing a Document. A LINQ expression filter. An optional partition key. Asynchronously counts how many documents match the filter condition. The type representing a Document. A LINQ expression filter. An optional partitionKey Counts how many documents match the filter condition. The type representing a Document. A LINQ expression filter. An optional partitionKey Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Asynchronously returns a projected document matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Returns a projected document matching the filter condition. The type representing a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Groups a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the grouping criteria. The type of the projected group. The grouping criteria. The projected group result. The partition key of your document, if any. Groups filtered a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the grouping criteria. The type of the projected group. A LINQ expression filter. The grouping criteria. The projected group result. The partition key of your document, if any. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. A LINQ expression filter. The property selector. Order of the sorting. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. A LINQ expression filter. The sort definition. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Asynchronously Updates a document. The type representing a Document. The document with the modifications you want to persist. Updates a document. The type representing a Document. The document with the modifications you want to persist. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The document you want to modify. The update definition for the document. Takes a document you want to modify and applies the update you have defined in MongoDb. The type representing a Document. The document you want to modify. The update definition for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document you want to modify. The field selector. The new value of the property field. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. Updates the property field with the given value update a property field in entities. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entity selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The partition key for the document. For the entities selected by the filter, updates the property field with the given value. The type representing a Document. The type of the field. The document filter. The field selector. The new value of the property field. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. For the entities selected by the filter, applies the update you have defined in MongoDb. The type representing a Document. The document filter. The update definition to apply. The value of the partition key. This class represents a basic document that can be stored in MongoDb. Your document must implement this class in order for the MongoDbRepository to handle them. The document constructor The Id of the document The datetime in UTC at which the document was added. The version of the schema of the document This class represents a basic document that can be stored in MongoDb. Your document must implement this class in order for the MongoDbRepository to handle them. The Primary Key, which must be decorated with the [BsonId] attribute if you want the MongoDb C# driver to consider it to be the document ID. A version number, to indicate the version of the schema. This class represents a basic document that can be stored in MongoDb. Your document must implement this class in order for the MongoDbRepository to handle them. Options for creating an index. Gets or sets a value indicating whether the index is a unique index. Gets or sets the index version for text indexes. Gets or sets the index version for 2dsphere indexes. Gets or sets a value indicating whether the index is a sparse index. Gets or sets the index name. Gets or sets the min value for 2d indexes. Gets or sets the max value for 2d indexes. Gets or sets the language override. Gets or sets when documents expire (used with TTL indexes). Gets or sets the default language. Gets or sets the size of a geohash bucket. Gets or sets the precision, in bits, used with geohash indexes. Gets or sets a value indicating whether to create the index in the background. Gets or sets the version of the index. This class represents a document that can be inserted in a collection that can be partitioned. The partition key allows for the creation of different collections having the same document schema. This can be useful if you are planning to build a Software as a Service (SaaS) Platform, or if you want to reduce indexing. You could for example insert Logs in different collections based on the week and year they where created, or their Log category/source. The partition key used to partition your collection. This class represents a document that can be inserted in a collection that can be partitioned. The partition key allows for the creation of different collections having the same document schema. This can be useful if you are planning to build a Software as a Service (SaaS) Platform, or if you want to reduce indexing. You could for example insert Logs in different collections based on the week and year they where created, or their Log category/source. The constructor, it needs a partition key. The name of the property used for partitioning the collection This will not be inserted into the collection. This partition key will be prepended to the collection name to create a new collection. The MongoDb context The IMongoClient from the official MongoDB driver The IMongoDatabase from the official MongoDB driver The constructor of the MongoDbContext, it needs an object implementing . An object implementing IMongoDatabase The constructor of the MongoDbContext, it needs a connection string and a database name. The connections string. The name of your database. Initialise an instance of a using a connection string The constructor of the MongoDbContext, it needs a connection string and a database name. The MongoClient. The name of your database. Returns a collection for a document type. Also handles document types with a partition key. The type representing a Document. The optional value of the partition key. Drops a collection, use very carefully. The type representing a Document. Sets the Guid representation of the MongoDB Driver. The new value of the GuidRepresentation Extracts the CollectionName attribute from the entity type, if any. The type representing a Document. The name of the collection in which the TDocument is stored. Initialize the Guid representation of the MongoDB Driver. Override this method to change the default GuidRepresentation. Given the document type and the partition key, returns the name of the collection it belongs to. The type representing a Document. The value of the partition key. The name of the collection. Very naively pluralizes a TDocument type name. The type representing a Document. The pluralized document name. The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. Its constructor must be given a connection string and a database name. The constructor taking a connection string and a database name. The connection string of the MongoDb server. The name of the database against which you want to perform operations. The constructor taking a . A mongodb context implementing The constructor taking a . A mongodb context implementing Asynchronously returns one document given its id. The type representing a Document. The type of the primary key for a Document. The Id of the document you want to get. An optional partition key. Returns one document given its id. The type representing a Document. The type of the primary key for a Document. The Id of the document you want to get. An optional partition key. Asynchronously returns one document given an expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns one document given an expression filter. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns a collection cursor. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns true if any of the document of the collection matches the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns true if any of the document of the collection matches the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Asynchronously returns a list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Returns a list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partition key. Asynchronously counts how many documents match the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partitionKey Counts how many documents match the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. An optional partitionKey Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by descending. An optional partitionKey. Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter. The document type. The type of the primary key. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to select the max value. An optional partitionKey. Gets the maximum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partitionKey. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Gets the minimum value of a property in a mongodb collections that is satisfying the filter. The document type. The type of the primary key. The type of the value used to order the query. A LINQ expression filter. A property selector to order by ascending. An optional partition key. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Sums the values of a selected field for a given filtered collection of documents. The type representing a Document. The type of the primary key. A LINQ expression filter. The field you want to sum. The partition key of your document, if any. Asynchronously returns a projected document matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Returns a projected document matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. A LINQ expression filter. The projection expression. An optional partition key. Asynchronously returns a list of projected documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. The type representing the model you want to project to. The document filter. The projection expression. An optional partition key. Groups filtered a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the primary key for a Document. The type of the grouping criteria. The type of the projected group. The grouping criteria. The projected group result. The partition key of your document, if any. Groups filtered a collection of documents given a grouping criteria, and returns a dictionary of listed document groups with keys having the different values of the grouping criteria. The type representing a Document. The type of the primary key for a Document. The type of the grouping criteria. The type of the projected group. A LINQ expression filter. The grouping criteria. The projected group result. The partition key of your document, if any. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The property selector. Order of the sorting. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Asynchronously returns a paginated list of the documents matching the filter condition. The type representing a Document. The type of the primary key for a Document. A LINQ expression filter. The sort definition. The number of documents you want to skip. Default value is 0. The number of documents you want to take. Default value is 50. An optional partition key. Gets a collections for a potentially partitioned document type. The document type. The type of the primary key. The document. Gets a collections for a potentially partitioned document type. The document type. The type of the primary key. The collection partition key. Gets a collections for a potentially partitioned document type. The document type. The document. Gets a collections for the type TDocument with a partition key. The document type. The type of the primary key. The collection partition key. The IdGenerator instance, used to generate Ids of different types. Generates a random value of a given type. The type of the value to generate. A value of type TKey. Container for registered Vocabularies. At present, only a single vocabulary is supported: Default. The default vocabulary used for singular/plural irregularities. Rules can be added to this vocabulary and will be picked up by called to Singularize() and Pluralize(). At this time, multiple vocabularies and removing existing rules are not supported. A container for exceptions to simple pluralization/singularization rules. Vocabularies.Default contains an extensive list of rules for US English. At this time, multiple vocabularies and removing existing rules are not supported. Adds a word to the vocabulary which cannot easily be pluralized/singularized by RegEx, e.g. "person" and "people". The singular form of the irregular word, e.g. "person". The plural form of the irregular word, e.g. "people". True to match these words on their own as well as at the end of longer words. False, otherwise. Adds an uncountable word to the vocabulary, e.g. "fish". Will be ignored when plurality is changed. Word to be added to the list of uncountables. Adds a rule to the vocabulary that does not follow trivial rules for pluralization, e.g. "bus" -> "buses" RegEx to be matched, case insensitive, e.g. "(bus)es$" RegEx replacement e.g. "$1" Adds a rule to the vocabulary that does not follow trivial rules for singularization, e.g. "vertices/indices -> "vertex/index" RegEx to be matched, case insensitive, e.g. ""(vert|ind)ices$"" RegEx replacement e.g. "$1ex" Pluralizes the provided input considering irregular words Word to be pluralized Normally you call Pluralize on singular words; but if you're unsure call it with false Singularizes the provided input considering irregular words Word to be singularized Normally you call Singularize on plural words; but if you're unsure call it with false Inflector extensions Pluralizes the provided input considering irregular words Word to be pluralized Normally you call Pluralize on singular words; but if you're unsure call it with false Singularizes the provided input considering irregular words Word to be singularized Normally you call Singularize on plural words; but if you're unsure call it with false By default, pascalize converts strings to UpperCamelCase also removing underscores Same as Pascalize except that the first character is lower case Separates the input words with underscore The string to be underscored Replaces underscores with dashes in the string Replaces underscores with hyphens in the string Extensions for the random number generator Returns a random long from min (inclusive) to max (exclusive) The given random instance The inclusive minimum bound The exclusive maximum bound. Must be greater than min Returns a random long from 0 (inclusive) to max (exclusive) The given random instance The exclusive maximum bound. Must be greater than 0 Returns a random long over all possible values of long (except long.MaxValue, similar to random.Next()) The given random instance ================================================ FILE: MongoDbGenericRepository/ReadOnlyMongoRepository.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation. /// Its constructor must be given a connection string and a database name. /// public abstract class ReadOnlyMongoRepository : ReadOnlyMongoRepository, IReadOnlyMongoRepository { /// /// The constructor taking a connection string and a database name. /// /// The connection string of the MongoDb server. /// The name of the database against which you want to perform operations. protected ReadOnlyMongoRepository(string connectionString, string databaseName = null) : base(connectionString, databaseName) { } /// /// The constructor taking a . /// /// A mongodb context implementing protected ReadOnlyMongoRepository(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } /// /// The constructor taking a . /// /// A mongodb context implementing protected ReadOnlyMongoRepository(IMongoDatabase mongoDatabase) : base(mongoDatabase) { } /// /// Gets a collections for a potentially partitioned document type. /// /// The document type. /// The type of the primary key. /// The document. /// public virtual IMongoCollection HandlePartitioned(TDocument document) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.HandlePartitioned(document); } /// /// Gets a collections for a potentially partitioned document type. /// /// The document type. /// The type of the primary key. /// The collection partition key. /// public virtual IMongoCollection HandlePartitioned(string partitionKey) where TDocument : IDocument where TKey : IEquatable { if (!string.IsNullOrEmpty(partitionKey)) { return GetCollection(partitionKey); } return GetCollection(); } /// /// Gets a collections for a potentially partitioned document type. /// /// The document type. /// The document. /// public virtual IMongoCollection HandlePartitioned(TDocument document) where TDocument : IDocument { return MongoDbReader.HandlePartitioned(document); } /// /// Gets a collections for the type TDocument with a partition key. /// /// The document type. /// The type of the primary key. /// The collection partition key. /// public virtual IMongoCollection GetCollection(string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetCollection(partitionKey); } #region Read TKey /// public virtual async Task GetByIdAsync(TKey id) where TDocument : IDocument where TKey : IEquatable { return await GetByIdAsync(id, null, CancellationToken.None); } /// public virtual async Task GetByIdAsync(TKey id, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await GetByIdAsync(id, null, cancellationToken); } /// public virtual async Task GetByIdAsync(TKey id, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await GetByIdAsync(id, partitionKey, CancellationToken.None); } /// public virtual async Task GetByIdAsync(TKey id, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.GetByIdAsync(id, partitionKey, cancellationToken); } /// public virtual TDocument GetById(TKey id) where TDocument : IDocument where TKey : IEquatable { return GetById(id, null, CancellationToken.None); } /// public virtual TDocument GetById(TKey id, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetById(id, null, cancellationToken); } /// public virtual TDocument GetById(TKey id, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetById(id, partitionKey, CancellationToken.None); } /// public virtual TDocument GetById(TKey id, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetById(id, partitionKey, cancellationToken); } /// public Task GetOneAsync(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable { return GetOneAsync(condition, null, null, CancellationToken.None); } /// public Task GetOneAsync(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetOneAsync(condition, null, null, cancellationToken); } /// public Task GetOneAsync(FilterDefinition condition, FindOptions findOption) where TDocument : IDocument where TKey : IEquatable { return GetOneAsync(condition, findOption, null, CancellationToken.None); } /// public Task GetOneAsync(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetOneAsync(condition, null, partitionKey, CancellationToken.None); } /// public Task GetOneAsync(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetOneAsync(condition, null, partitionKey, cancellationToken); } /// public Task GetOneAsync(FilterDefinition condition, FindOptions findOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetOneAsync(condition, findOption, null, cancellationToken); } /// public Task GetOneAsync(FilterDefinition condition, FindOptions findOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetOneAsync(condition, findOption, partitionKey, CancellationToken.None); } /// public Task GetOneAsync( FilterDefinition condition, FindOptions findOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetOneAsync(condition, findOption, partitionKey, cancellationToken); } /// public TDocument GetOne(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable { return GetOne(condition, null, null, CancellationToken.None); } /// public TDocument GetOne(FilterDefinition condition, FindOptions findOption) where TDocument : IDocument where TKey : IEquatable { return GetOne(condition, findOption, null, CancellationToken.None); } /// public TDocument GetOne(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetOne(condition, null, partitionKey, CancellationToken.None); } /// public TDocument GetOne(FilterDefinition condition, FindOptions findOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetOne(condition, findOption, partitionKey, CancellationToken.None); } /// public TDocument GetOne(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetOne(condition, null, null, cancellationToken); } /// public TDocument GetOne(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetOne(condition, null, partitionKey, cancellationToken); } /// public TDocument GetOne(FilterDefinition condition, FindOptions findOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetOne(condition, findOption, null, cancellationToken); } /// public TDocument GetOne( FilterDefinition condition, FindOptions findOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetOne(condition, findOption, partitionKey, cancellationToken); } /// public virtual async Task GetOneAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return await GetOneAsync(filter, null, CancellationToken.None); } /// public virtual async Task GetOneAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await GetOneAsync(filter, partitionKey, CancellationToken.None); } /// public virtual async Task GetOneAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await GetOneAsync(filter, null, cancellationToken); } /// public virtual async Task GetOneAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.GetOneAsync(filter, partitionKey, cancellationToken); } /// public virtual TDocument GetOne(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return GetOne(filter, null, CancellationToken.None); } /// public virtual TDocument GetOne(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetOne(filter, partitionKey, CancellationToken.None); } /// public virtual TDocument GetOne(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetOne(filter, null, cancellationToken); } /// public virtual TDocument GetOne(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetOne(filter, partitionKey, cancellationToken); } /// public virtual IFindFluent GetCursor(Expression> filter, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetCursor(filter, partitionKey); } /// public Task AnyAsync(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable { return AnyAsync(condition, null, null, CancellationToken.None); } /// public Task AnyAsync(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return AnyAsync(condition, null, partitionKey, CancellationToken.None); } /// public Task AnyAsync(FilterDefinition condition, CountOptions countOption) where TDocument : IDocument where TKey : IEquatable { return AnyAsync(condition, countOption, null, CancellationToken.None); } /// public Task AnyAsync(FilterDefinition condition, CountOptions countOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return AnyAsync(condition, countOption, partitionKey, CancellationToken.None); } /// public Task AnyAsync(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return AnyAsync(condition, null, null, cancellationToken); } /// public Task AnyAsync(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return AnyAsync(condition, null, partitionKey, cancellationToken); } /// public Task AnyAsync(FilterDefinition condition, CountOptions countOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return AnyAsync(condition, countOption, null, cancellationToken); } /// public Task AnyAsync( FilterDefinition condition, CountOptions countOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.AnyAsync(condition, countOption, partitionKey, cancellationToken); } /// public bool Any(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable { return Any(condition, null, null, CancellationToken.None); } /// public bool Any(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return Any(condition, null, partitionKey, CancellationToken.None); } /// public bool Any(FilterDefinition condition, CountOptions countOption) where TDocument : IDocument where TKey : IEquatable { return Any(condition, countOption, null, CancellationToken.None); } /// public bool Any(FilterDefinition condition, CountOptions countOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.Any(condition, countOption, partitionKey, CancellationToken.None); } /// public bool Any(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return Any(condition, null, null, cancellationToken); } /// public bool Any(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return Any(condition, null, partitionKey, cancellationToken); } /// public bool Any(FilterDefinition condition, CountOptions countOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return Any(condition, countOption, null, cancellationToken); } /// public bool Any( FilterDefinition condition, CountOptions countOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.Any(condition, countOption, partitionKey, cancellationToken); } /// public virtual async Task AnyAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return await AnyAsync(filter, null, CancellationToken.None); } /// public virtual async Task AnyAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await AnyAsync(filter, null, cancellationToken); } /// public virtual async Task AnyAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await AnyAsync(filter, partitionKey, CancellationToken.None); } /// public virtual async Task AnyAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.AnyAsync(filter, partitionKey, cancellationToken); } /// public virtual bool Any(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.Any(filter, null, CancellationToken.None); } /// public virtual bool Any(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.Any(filter, null, cancellationToken); } /// public virtual bool Any(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return Any(filter, partitionKey, CancellationToken.None); } /// public virtual bool Any(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.Any(filter, partitionKey, cancellationToken); } /// public Task> GetAllAsync(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable { return GetAllAsync(condition, null, null, CancellationToken.None); } /// public Task> GetAllAsync(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetAllAsync(condition, null, partitionKey, CancellationToken.None); } /// public Task> GetAllAsync(FilterDefinition condition, FindOptions findOption) where TDocument : IDocument where TKey : IEquatable { return GetAllAsync(condition, findOption, null, CancellationToken.None); } /// public Task> GetAllAsync(FilterDefinition condition, FindOptions findOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetAllAsync(condition, findOption, partitionKey, CancellationToken.None); } /// public Task> GetAllAsync(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetAllAsync(condition, null, null, cancellationToken); } /// public Task> GetAllAsync( FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetAllAsync(condition, null, partitionKey, cancellationToken); } /// public Task> GetAllAsync( FilterDefinition condition, FindOptions findOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetAllAsync(condition, findOption, null, cancellationToken); } /// public Task> GetAllAsync( FilterDefinition condition, FindOptions findOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetAllAsync(condition, findOption, partitionKey, cancellationToken); } /// public List GetAll(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable { return GetAll(condition, null, null, CancellationToken.None); } /// public List GetAll(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetAll(condition, null, null, cancellationToken); } /// public List GetAll(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetAll(condition, null, partitionKey, CancellationToken.None); } /// public List GetAll(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetAll(condition, null, partitionKey, cancellationToken); } /// public List GetAll(FilterDefinition condition, FindOptions findOption) where TDocument : IDocument where TKey : IEquatable { return GetAll(condition, findOption, null, CancellationToken.None); } /// public List GetAll(FilterDefinition condition, FindOptions findOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetAll(condition, findOption, null, cancellationToken); } /// public List GetAll(FilterDefinition condition, FindOptions findOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetAll(condition, findOption, partitionKey, CancellationToken.None); } /// public List GetAll( FilterDefinition condition, FindOptions findOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetAll(condition, findOption, partitionKey, cancellationToken); } /// public virtual async Task> GetAllAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return await GetAllAsync(filter, null, CancellationToken.None); } /// public virtual async Task> GetAllAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await GetAllAsync(filter, null, cancellationToken); } /// public virtual async Task> GetAllAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await GetAllAsync(filter, partitionKey, CancellationToken.None); } /// public virtual async Task> GetAllAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.GetAllAsync(filter, partitionKey, cancellationToken); } /// public virtual List GetAll(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return GetAll(filter, null, CancellationToken.None); } /// public virtual List GetAll(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetAll(filter, null, cancellationToken); } /// public virtual List GetAll(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetAll(filter, partitionKey, CancellationToken.None); } /// public virtual List GetAll( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetAll(filter, partitionKey, cancellationToken); } /// public Task CountAsync(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable { return CountAsync(condition, null, null, CancellationToken.None); } /// public Task CountAsync(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return CountAsync(condition, null, null, cancellationToken); } /// public Task CountAsync(FilterDefinition condition, CountOptions countOption) where TDocument : IDocument where TKey : IEquatable { return CountAsync(condition, countOption, null, CancellationToken.None); } /// public Task CountAsync(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return CountAsync(condition, null, partitionKey, CancellationToken.None); } /// public Task CountAsync(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return CountAsync(condition, null, partitionKey, cancellationToken); } /// public Task CountAsync(FilterDefinition condition, CountOptions countOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return CountAsync(condition, countOption, null, cancellationToken); } /// public Task CountAsync(FilterDefinition condition, CountOptions countOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return CountAsync(condition, countOption, partitionKey, CancellationToken.None); } /// public Task CountAsync( FilterDefinition condition, CountOptions countOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.CountAsync(condition, countOption, partitionKey, cancellationToken); } /// public long Count(FilterDefinition condition) where TDocument : IDocument where TKey : IEquatable { return Count(condition, null, null, CancellationToken.None); } /// public long Count(FilterDefinition condition, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return Count(condition, null, null, cancellationToken); } /// public long Count(FilterDefinition condition, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return Count(condition, null, partitionKey, CancellationToken.None); } /// public long Count(FilterDefinition condition, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return Count(condition, null, partitionKey, cancellationToken); } /// public long Count(FilterDefinition condition, CountOptions countOption) where TDocument : IDocument where TKey : IEquatable { return Count(condition, countOption, null, CancellationToken.None); } /// public long Count(FilterDefinition condition, CountOptions countOption, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return Count(condition, countOption, null, cancellationToken); } /// public long Count(FilterDefinition condition, CountOptions countOption, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return Count(condition, countOption, partitionKey, CancellationToken.None); } /// public long Count( FilterDefinition condition, CountOptions countOption, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.Count(condition, countOption, partitionKey, cancellationToken); } /// public virtual async Task CountAsync(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return await CountAsync(filter, null, CancellationToken.None); } /// public virtual async Task CountAsync(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await CountAsync(filter, null, cancellationToken); } /// public virtual async Task CountAsync(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await CountAsync(filter, partitionKey, CancellationToken.None); } /// public virtual async Task CountAsync( Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.CountAsync(filter, partitionKey, cancellationToken); } /// public virtual long Count(Expression> filter) where TDocument : IDocument where TKey : IEquatable { return Count(filter, null, CancellationToken.None); } /// public virtual long Count(Expression> filter, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return Count(filter, null, cancellationToken); } /// public virtual long Count(Expression> filter, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return Count(filter, partitionKey, CancellationToken.None); } /// public virtual long Count(Expression> filter, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.Count(filter, partitionKey, cancellationToken); } /// public virtual async Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector) where TDocument : IDocument where TKey : IEquatable { return await GetByMaxAsync(filter, maxValueSelector, null, CancellationToken.None); } /// public virtual async Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await GetByMaxAsync(filter, maxValueSelector, null, cancellationToken); } /// public virtual async Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await GetByMaxAsync(filter, maxValueSelector, partitionKey, CancellationToken.None); } /// public virtual async Task GetByMaxAsync( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.GetByMaxAsync(filter, maxValueSelector, partitionKey, cancellationToken); } /// public virtual TDocument GetByMax(Expression> filter, Expression> maxValueSelector) where TDocument : IDocument where TKey : IEquatable { return GetByMax(filter, maxValueSelector, null, CancellationToken.None); } /// public virtual TDocument GetByMax( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetByMax(filter, maxValueSelector, null, cancellationToken); } /// public virtual TDocument GetByMax( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetByMax(filter, maxValueSelector, partitionKey, CancellationToken.None); } /// public virtual TDocument GetByMax( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetByMax(filter, maxValueSelector, partitionKey, cancellationToken); } /// public virtual async Task GetByMinAsync( Expression> filter, Expression> minValueSelector) where TDocument : IDocument where TKey : IEquatable { return await GetByMinAsync(filter, minValueSelector, null, CancellationToken.None); } /// public virtual async Task GetByMinAsync( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await GetByMinAsync(filter, minValueSelector, null, cancellationToken); } /// public virtual async Task GetByMinAsync( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await GetByMinAsync(filter, minValueSelector, partitionKey, CancellationToken.None); } /// public virtual async Task GetByMinAsync( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.GetByMinAsync(filter, minValueSelector, partitionKey, cancellationToken); } /// public virtual TDocument GetByMin(Expression> filter, Expression> minValueSelector) where TDocument : IDocument where TKey : IEquatable { return GetByMin(filter, minValueSelector, null, CancellationToken.None); } /// public virtual TDocument GetByMin( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetByMin(filter, minValueSelector, null, cancellationToken); } /// public virtual TDocument GetByMin( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetByMin(filter, minValueSelector, partitionKey, CancellationToken.None); } /// public virtual TDocument GetByMin( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetByMin(filter, minValueSelector, partitionKey, cancellationToken); } /// public virtual async Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector) where TDocument : IDocument where TKey : IEquatable { return await GetMaxValueAsync(filter, maxValueSelector, null, CancellationToken.None); } /// public virtual async Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await GetMaxValueAsync(filter, maxValueSelector, null, cancellationToken); } /// public virtual async Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await GetMaxValueAsync(filter, maxValueSelector, partitionKey, CancellationToken.None); } /// public virtual async Task GetMaxValueAsync( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.GetMaxValueAsync(filter, maxValueSelector, partitionKey, cancellationToken); } /// public virtual TValue GetMaxValue( Expression> filter, Expression> maxValueSelector) where TDocument : IDocument where TKey : IEquatable { return GetMaxValue(filter, maxValueSelector, null, CancellationToken.None); } /// public virtual TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetMaxValue(filter, maxValueSelector, null, cancellationToken); } /// public virtual TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetMaxValue(filter, maxValueSelector, partitionKey, CancellationToken.None); } /// public virtual TValue GetMaxValue( Expression> filter, Expression> maxValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetMaxValue(filter, maxValueSelector, partitionKey, cancellationToken); } /// public virtual async Task GetMinValueAsync( Expression> filter, Expression> minValueSelector) where TDocument : IDocument where TKey : IEquatable { return await GetMinValueAsync(filter, minValueSelector, null, CancellationToken.None); } /// public virtual async Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await GetMinValueAsync(filter, minValueSelector, null, cancellationToken); } /// public virtual async Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await GetMinValueAsync(filter, minValueSelector, partitionKey, CancellationToken.None); } /// public virtual async Task GetMinValueAsync( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.GetMinValueAsync(filter, minValueSelector, partitionKey, cancellationToken); } /// public virtual TValue GetMinValue( Expression> filter, Expression> minValueSelector) where TDocument : IDocument where TKey : IEquatable { return GetMinValue(filter, minValueSelector, null, CancellationToken.None); } /// public virtual TValue GetMinValue( Expression> filter, Expression> minValueSelector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return GetMinValue(filter, minValueSelector, null, cancellationToken); } /// public virtual TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return GetMinValue(filter, minValueSelector, partitionKey, CancellationToken.None); } /// public virtual TValue GetMinValue( Expression> filter, Expression> minValueSelector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.GetMinValue(filter, minValueSelector, partitionKey, cancellationToken); } #endregion #region Sum TKey /// public virtual async Task SumByAsync(Expression> filter, Expression> selector) where TDocument : IDocument where TKey : IEquatable { return await SumByAsync(filter, selector, null, CancellationToken.None); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await SumByAsync(filter, selector, null, cancellationToken); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await SumByAsync(filter, selector, partitionKey, CancellationToken.None); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.SumByAsync(filter, selector, partitionKey, cancellationToken); } /// public virtual int SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.SumBy(filter, selector, partitionKey); } /// public virtual async Task SumByAsync(Expression> filter, Expression> selector) where TDocument : IDocument where TKey : IEquatable { return await SumByAsync(filter, selector, null, CancellationToken.None); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await SumByAsync(filter, selector, null, cancellationToken); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey) where TDocument : IDocument where TKey : IEquatable { return await SumByAsync(filter, selector, partitionKey, CancellationToken.None); } /// public virtual async Task SumByAsync( Expression> filter, Expression> selector, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable { return await MongoDbReader.SumByAsync(filter, selector, partitionKey, cancellationToken); } /// public virtual decimal SumBy( Expression> filter, Expression> selector, string partitionKey = null) where TDocument : IDocument where TKey : IEquatable { return MongoDbReader.SumBy(filter, selector, partitionKey); } #endregion Sum TKey #region Project TKey /// public virtual async Task ProjectOneAsync( Expression> filter, Expression> projection) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await ProjectOneAsync(filter, projection, null, CancellationToken.None); } /// public virtual async Task ProjectOneAsync( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await ProjectOneAsync(filter, projection, null, cancellationToken); } /// public virtual async Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await ProjectOneAsync(filter, projection, partitionKey, CancellationToken.None); } /// public virtual async Task ProjectOneAsync( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await MongoDbReader.ProjectOneAsync(filter, projection, partitionKey, cancellationToken); } /// public virtual TProjection ProjectOne( Expression> filter, Expression> projection) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return ProjectOne(filter, projection, null, CancellationToken.None); } /// public virtual TProjection ProjectOne( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return ProjectOne(filter, projection, null, cancellationToken); } /// public virtual TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return ProjectOne(filter, projection, partitionKey, CancellationToken.None); } /// public virtual TProjection ProjectOne( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return MongoDbReader.ProjectOne(filter, projection, partitionKey, cancellationToken); } /// public virtual async Task> ProjectManyAsync( Expression> filter, Expression> projection) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await ProjectManyAsync(filter, projection, null, CancellationToken.None); } /// public virtual async Task> ProjectManyAsync( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await ProjectManyAsync(filter, projection, null, cancellationToken); } /// public virtual async Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await ProjectManyAsync(filter, projection, partitionKey, CancellationToken.None); } /// public virtual async Task> ProjectManyAsync( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return await MongoDbReader.ProjectManyAsync(filter, projection, partitionKey, cancellationToken); } /// public virtual List ProjectMany( Expression> filter, Expression> projection) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return ProjectMany(filter, projection, null, CancellationToken.None); } /// public virtual List ProjectMany( Expression> filter, Expression> projection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return ProjectMany(filter, projection, null, cancellationToken); } /// public virtual List ProjectMany( Expression> filter, Expression> projection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return ProjectMany(filter, projection, partitionKey, CancellationToken.None); } /// public virtual List ProjectMany( Expression> filter, Expression> projection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class { return MongoDbReader.ProjectMany(filter, projection, partitionKey, cancellationToken); } #endregion Project TKey #region Group By TKey /// public virtual List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { return GroupBy(groupingCriteria, groupProjection, null, CancellationToken.None); } /// public virtual List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { return GroupBy(groupingCriteria, groupProjection, null, cancellationToken); } /// public virtual List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { return GroupBy(groupingCriteria, groupProjection, partitionKey, CancellationToken.None); } /// public virtual List GroupBy( Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { return MongoDbReader.GroupBy(groupingCriteria, groupProjection, partitionKey, cancellationToken); } /// public virtual List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { return GroupBy(filter, groupingCriteria, groupProjection, null, CancellationToken.None); } /// public virtual List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { return GroupBy(filter, groupingCriteria, groupProjection, null, cancellationToken); } /// public virtual List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { return GroupBy(filter, groupingCriteria, groupProjection, partitionKey, CancellationToken.None); } /// public virtual List GroupBy( Expression> filter, Expression> groupingCriteria, Expression, TProjection>> groupProjection, string partitionKey, CancellationToken cancellationToken) where TDocument : IDocument where TKey : IEquatable where TProjection : class, new() { return MongoDbReader.GroupBy(filter, groupingCriteria, groupProjection, partitionKey, cancellationToken); } #endregion Group By TKey #region Pagination /// public virtual async Task> GetSortedPaginatedAsync( Expression> filter, Expression> sortSelector, bool ascending = true, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { var sorting = ascending ? Builders.Sort.Ascending(sortSelector) : Builders.Sort.Descending(sortSelector); return await HandlePartitioned(partitionKey) .Find(filter) .Sort(sorting) .Skip(skipNumber) .Limit(takeNumber) .ToListAsync(cancellationToken); } /// public virtual async Task> GetSortedPaginatedAsync( Expression> filter, SortDefinition sortDefinition, int skipNumber = 0, int takeNumber = 50, string partitionKey = null, CancellationToken cancellationToken = default) where TDocument : IDocument where TKey : IEquatable { return await HandlePartitioned(partitionKey) .Find(filter) .Sort(sortDefinition) .Skip(skipNumber) .Limit(takeNumber) .ToListAsync(cancellationToken); } #endregion Pagination } } ================================================ FILE: MongoDbGenericRepository/Utils/IdGenerator.cs ================================================ using MongoDB.Bson; using System; namespace MongoDbGenericRepository.Utils { /// /// The IdGenerator instance, used to generate Ids of different types. /// public static class IdGenerator { private static readonly Random Random = new Random(); /// /// Generates a random value of a given type. /// /// The type of the value to generate. /// A value of type TKey. public static TKey GetId() { var idTypeName = typeof(TKey).Name; switch (idTypeName) { case "Guid": return (TKey)(object)Guid.NewGuid(); case "Int16": return (TKey)(object)Random.Next(1, short.MaxValue); case "Int32": return (TKey)(object)Random.Next(1, int.MaxValue); case "Int64": return (TKey)(object)(Random.NextLong(1, long.MaxValue)); case "String": return (TKey)(object)Guid.NewGuid().ToString(); case "ObjectId": return (TKey)(object)ObjectId.GenerateNewId(); } throw new ArgumentException($"{idTypeName} is not a supported Id type, the Id of the document cannot be set."); } } } ================================================ FILE: MongoDbGenericRepository/Utils/Pluralization.cs ================================================ //The Inflector class was cloned from Inflector (https://github.com/srkirkland/Inflector) //The MIT License (MIT) //Copyright (c) 2013 Scott Kirkland //Permission is hereby granted, free of charge, to any person obtaining a copy of //this software and associated documentation files (the "Software"), to deal in //the Software without restriction, including without limitation the rights to //use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of //the Software, and to permit persons to whom the Software is furnished to do so, //subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS //FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR //COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER //IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN //CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //Vocabulary and Vocabularies classes were copied from Humanizer.Inflections (https://github.com/Humanizr/Humanizer) //The MIT License(MIT) //Copyright(c) 2012-2014 Mehdi Khalili //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. //============================================================================== //Inflector (https://github.com/srkirkland/Inflector) //The MIT License (MIT) //Copyright (c) 2013 Scott Kirkland //============================================================================== //ByteSize (https://github.com/omar/ByteSize) //The MIT License (MIT) //Copyright (c) 2013-2014 Omar Khudeira (http://omar.io) //============================================================================== using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading; namespace MongoDbGenericRepository.Utils { /// /// Container for registered Vocabularies. At present, only a single vocabulary is supported: Default. /// public static class Vocabularies { private static readonly Lazy Instance; static Vocabularies() { Instance = new Lazy(BuildDefault, LazyThreadSafetyMode.PublicationOnly); } /// /// The default vocabulary used for singular/plural irregularities. /// Rules can be added to this vocabulary and will be picked up by called to Singularize() and Pluralize(). /// At this time, multiple vocabularies and removing existing rules are not supported. /// public static Vocabulary Default => Instance.Value; private static Vocabulary BuildDefault() { var _default = new Vocabulary(); _default.AddPlural("$", "s"); _default.AddPlural("s$", "s"); _default.AddPlural("(ax|test)is$", "$1es"); _default.AddPlural("(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)us$", "$1i"); _default.AddPlural("(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)$", "$1es"); _default.AddPlural("(buffal|tomat|volcan|ech|embarg|her|mosquit|potat|torped|vet)o$", "$1oes"); _default.AddPlural("([dti])um$", "$1a"); _default.AddPlural("sis$", "ses"); _default.AddPlural("(?:([^f])fe|([lr])f)$", "$1$2ves"); _default.AddPlural("(hive)$", "$1s"); _default.AddPlural("([^aeiouy]|qu)y$", "$1ies"); _default.AddPlural("(x|ch|ss|sh)$", "$1es"); _default.AddPlural("(matr|vert|ind|d)ix|ex$", "$1ices"); _default.AddPlural("([m|l])ouse$", "$1ice"); _default.AddPlural("^(ox)$", "$1en"); _default.AddPlural("(quiz)$", "$1zes"); _default.AddPlural("(buz|blit|walt)z$", "$1zes"); _default.AddPlural("(hoo|lea|loa|thie)f$", "$1ves"); _default.AddPlural("(alumn|alg|larv|vertebr)a$", "$1ae"); _default.AddPlural("(criteri|phenomen)on$", "$1a"); _default.AddSingular("s$", ""); _default.AddSingular("(n)ews$", "$1ews"); _default.AddSingular("([dti])a$", "$1um"); _default.AddSingular("(analy|ba|diagno|parenthe|progno|synop|the|ellip|empha|neuro|oa|paraly)ses$", "$1sis"); _default.AddSingular("([^f])ves$", "$1fe"); _default.AddSingular("(hive)s$", "$1"); _default.AddSingular("(tive)s$", "$1"); _default.AddSingular("([lr]|hoo|lea|loa|thie)ves$", "$1f"); _default.AddSingular("(^zomb)?([^aeiouy]|qu)ies$", "$2y"); _default.AddSingular("(s)eries$", "$1eries"); _default.AddSingular("(m)ovies$", "$1ovie"); _default.AddSingular("(x|ch|ss|sh)es$", "$1"); _default.AddSingular("([m|l])ice$", "$1ouse"); _default.AddSingular("(o)es$", "$1"); _default.AddSingular("(shoe)s$", "$1"); _default.AddSingular("(cris|ax|test)es$", "$1is"); _default.AddSingular("(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)i$", "$1us"); _default.AddSingular("(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)es$", "$1"); _default.AddSingular("^(ox)en", "$1"); _default.AddSingular("(matr|d)ices$", "$1ix"); _default.AddSingular("(vert|ind)ices$", "$1ex"); _default.AddSingular("(quiz)zes$", "$1"); _default.AddSingular("(buz|blit|walt)zes$", "$1z"); _default.AddSingular("(alumn|alg|larv|vertebr)ae$", "$1a"); _default.AddSingular("(criteri|phenomen)a$", "$1on"); _default.AddIrregular("person", "people"); _default.AddIrregular("man", "men"); _default.AddIrregular("child", "children"); _default.AddIrregular("sex", "sexes"); _default.AddIrregular("move", "moves"); _default.AddIrregular("goose", "geese"); _default.AddIrregular("wave", "waves"); _default.AddIrregular("die", "dice"); _default.AddIrregular("foot", "feet"); _default.AddIrregular("tooth", "teeth"); _default.AddIrregular("curriculum", "curricula"); _default.AddIrregular("database", "databases"); _default.AddIrregular("zombie", "zombies"); _default.AddIrregular("is", "are", matchEnding: false); _default.AddIrregular("that", "those", matchEnding: false); _default.AddIrregular("this", "these", matchEnding: false); _default.AddIrregular("bus", "buses", matchEnding: false); _default.AddUncountable("equipment"); _default.AddUncountable("information"); _default.AddUncountable("rice"); _default.AddUncountable("money"); _default.AddUncountable("species"); _default.AddUncountable("series"); _default.AddUncountable("fish"); _default.AddUncountable("sheep"); _default.AddUncountable("deer"); _default.AddUncountable("aircraft"); _default.AddUncountable("oz"); _default.AddUncountable("tsp"); _default.AddUncountable("tbsp"); _default.AddUncountable("ml"); _default.AddUncountable("l"); _default.AddUncountable("water"); _default.AddUncountable("waters"); _default.AddUncountable("semen"); _default.AddUncountable("sperm"); _default.AddUncountable("bison"); _default.AddUncountable("grass"); _default.AddUncountable("hair"); _default.AddUncountable("mud"); _default.AddUncountable("elk"); _default.AddUncountable("luggage"); _default.AddUncountable("moose"); _default.AddUncountable("offspring"); _default.AddUncountable("salmon"); _default.AddUncountable("shrimp"); _default.AddUncountable("someone"); _default.AddUncountable("swine"); _default.AddUncountable("trout"); _default.AddUncountable("tuna"); _default.AddUncountable("corps"); _default.AddUncountable("scissors"); _default.AddUncountable("means"); return _default; } } /// /// A container for exceptions to simple pluralization/singularization rules. /// Vocabularies.Default contains an extensive list of rules for US English. /// At this time, multiple vocabularies and removing existing rules are not supported. /// public class Vocabulary { internal Vocabulary() { } private readonly List _plurals = new List(); private readonly List _singulars = new List(); private readonly List _uncountables = new List(); /// /// Adds a word to the vocabulary which cannot easily be pluralized/singularized by RegEx, e.g. "person" and "people". /// /// The singular form of the irregular word, e.g. "person". /// The plural form of the irregular word, e.g. "people". /// True to match these words on their own as well as at the end of longer words. False, otherwise. public void AddIrregular(string singular, string plural, bool matchEnding = true) { if (matchEnding) { AddPlural("(" + singular[0] + ")" + singular.Substring(1) + "$", "$1" + plural.Substring(1)); AddSingular("(" + plural[0] + ")" + plural.Substring(1) + "$", "$1" + singular.Substring(1)); } else { AddPlural($"^{singular}$", plural); AddSingular($"^{plural}$", singular); } } /// /// Adds an uncountable word to the vocabulary, e.g. "fish". Will be ignored when plurality is changed. /// /// Word to be added to the list of uncountables. public void AddUncountable(string word) { _uncountables.Add(word.ToLower()); } /// /// Adds a rule to the vocabulary that does not follow trivial rules for pluralization, e.g. "bus" -> "buses" /// /// RegEx to be matched, case insensitive, e.g. "(bus)es$" /// RegEx replacement e.g. "$1" public void AddPlural(string rule, string replacement) { _plurals.Add(new Rule(rule, replacement)); } /// /// Adds a rule to the vocabulary that does not follow trivial rules for singularization, e.g. "vertices/indices -> "vertex/index" /// /// RegEx to be matched, case insensitive, e.g. ""(vert|ind)ices$"" /// RegEx replacement e.g. "$1ex" public void AddSingular(string rule, string replacement) { _singulars.Add(new Rule(rule, replacement)); } /// /// Pluralizes the provided input considering irregular words /// /// Word to be pluralized /// Normally you call Pluralize on singular words; but if you're unsure call it with false /// public string Pluralize(string word, bool inputIsKnownToBeSingular = true) { var result = ApplyRules(_plurals, word); if (inputIsKnownToBeSingular) return result; var asSingular = ApplyRules(_singulars, word); var asSingularAsPlural = ApplyRules(_plurals, asSingular); if (asSingular != null && asSingular != word && asSingular + "s" != word && asSingularAsPlural == word && result != word) return word; return result; } /// /// Singularizes the provided input considering irregular words /// /// Word to be singularized /// Normally you call Singularize on plural words; but if you're unsure call it with false /// public string Singularize(string word, bool inputIsKnownToBePlural = true) { var result = ApplyRules(_singulars, word); if (inputIsKnownToBePlural) return result; // the Plurality is unknown so we should check all possibilities var asPlural = ApplyRules(_plurals, word); var asPluralAsSingular = ApplyRules(_singulars, asPlural); if (asPlural != word && word + "s" != asPlural && asPluralAsSingular == word && result != word) return word; return result ?? word; } private string ApplyRules(IList rules, string word) { if (word == null) return null; if (IsUncountable(word)) return word; var result = word; for (var i = rules.Count - 1; i >= 0; i--) { if ((result = rules[i].Apply(word)) != null) break; } return result; } private bool IsUncountable(string word) { return _uncountables.Contains(word.ToLower()); } private class Rule { private readonly Regex _regex; private readonly string _replacement; public Rule(string pattern, string replacement) { _regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); _replacement = replacement; } public string Apply(string word) { if (!_regex.IsMatch(word)) return null; return _regex.Replace(word, _replacement); } } } /// /// Inflector extensions /// public static class InflectorExtensions { /// /// Pluralizes the provided input considering irregular words /// /// Word to be pluralized /// Normally you call Pluralize on singular words; but if you're unsure call it with false /// public static string Pluralize(this string word, bool inputIsKnownToBeSingular = true) { return Vocabularies.Default.Pluralize(word, inputIsKnownToBeSingular); } /// /// Singularizes the provided input considering irregular words /// /// Word to be singularized /// Normally you call Singularize on plural words; but if you're unsure call it with false /// public static string Singularize(this string word, bool inputIsKnownToBePlural = true) { return Vocabularies.Default.Singularize(word, inputIsKnownToBePlural); } /// /// By default, pascalize converts strings to UpperCamelCase also removing underscores /// /// /// public static string Pascalize(this string input) { return Regex.Replace(input, "(?:^|_)(.)", match => match.Groups[1].Value.ToUpper()); } /// /// Same as Pascalize except that the first character is lower case /// /// /// public static string Camelize(this string input) { var word = Pascalize(input); return word.Substring(0, 1).ToLower() + word.Substring(1); } /// /// Separates the input words with underscore /// /// The string to be underscored /// public static string Underscore(this string input) { return Regex.Replace( Regex.Replace( Regex.Replace(input, @"([A-Z]+)([A-Z][a-z])", "$1_$2"), @"([a-z\d])([A-Z])", "$1_$2"), @"[-\s]", "_").ToLower(); } /// /// Replaces underscores with dashes in the string /// /// /// public static string Dasherize(this string underscoredWord) { return underscoredWord.Replace('_', '-'); } /// /// Replaces underscores with hyphens in the string /// /// /// public static string Hyphenate(this string underscoredWord) { return Dasherize(underscoredWord); } } } ================================================ FILE: MongoDbGenericRepository/Utils/RandomExtensions.cs ================================================ using System; namespace MongoDbGenericRepository.Utils { // Thanks BlueRaja - Danny Pflughoeft https://stackoverflow.com/a/13095144/5103354 /// /// Extensions for the random number generator /// public static class RandomExtensions { /// /// Returns a random long from min (inclusive) to max (exclusive) /// /// The given random instance /// The inclusive minimum bound /// The exclusive maximum bound. Must be greater than min public static long NextLong(this Random random, long min, long max) { if (max <= min) throw new ArgumentOutOfRangeException("max", "max must be > min!"); //Working with ulong so that modulo works correctly with values > long.MaxValue ulong uRange = (ulong)(max - min); //Prevent a modulo bias; see https://stackoverflow.com/a/10984975/238419 //for more information. //In the worst case, the expected number of calls is 2 (though usually it's //much closer to 1) so this loop doesn't really hurt performance at all. ulong ulongRand; do { byte[] buf = new byte[8]; random.NextBytes(buf); ulongRand = (ulong)BitConverter.ToInt64(buf, 0); } while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange); return (long)(ulongRand % uRange) + min; } /// /// Returns a random long from 0 (inclusive) to max (exclusive) /// /// The given random instance /// The exclusive maximum bound. Must be greater than 0 public static long NextLong(this Random random, long max) { return random.NextLong(0, max); } /// /// Returns a random long over all possible values of long (except long.MaxValue, similar to /// random.Next()) /// /// The given random instance public static long NextLong(this Random random) { return random.NextLong(long.MinValue, long.MaxValue); } } } ================================================ FILE: MongoDbGenericRepository/_rels/.rels ================================================ ================================================ FILE: MongoDbGenericRepository.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.12.35521.163 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IntegrationTests", "IntegrationTests\IntegrationTests.csproj", "{A484A355-A015-40CC-9B35-A4E872421128}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MongoDbGenericRepository", "MongoDbGenericRepository\MongoDbGenericRepository.csproj", "{EFC776C4-2AF3-440C-BE80-3FBE335817A5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CoreIntegrationTests", "CoreIntegrationTests\CoreIntegrationTests.csproj", "{C640C106-7A25-4E49-A0CF-E4F248E5A97F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CoreUnitTests", "CoreUnitTests\CoreUnitTests.csproj", "{8BE513ED-84F4-47E1-946D-84958CF95E6B}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A484A355-A015-40CC-9B35-A4E872421128}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A484A355-A015-40CC-9B35-A4E872421128}.Debug|Any CPU.Build.0 = Debug|Any CPU {A484A355-A015-40CC-9B35-A4E872421128}.Release|Any CPU.ActiveCfg = Release|Any CPU {A484A355-A015-40CC-9B35-A4E872421128}.Release|Any CPU.Build.0 = Release|Any CPU {EFC776C4-2AF3-440C-BE80-3FBE335817A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EFC776C4-2AF3-440C-BE80-3FBE335817A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {EFC776C4-2AF3-440C-BE80-3FBE335817A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {EFC776C4-2AF3-440C-BE80-3FBE335817A5}.Release|Any CPU.Build.0 = Release|Any CPU {C640C106-7A25-4E49-A0CF-E4F248E5A97F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C640C106-7A25-4E49-A0CF-E4F248E5A97F}.Debug|Any CPU.Build.0 = Debug|Any CPU {C640C106-7A25-4E49-A0CF-E4F248E5A97F}.Release|Any CPU.ActiveCfg = Release|Any CPU {C640C106-7A25-4E49-A0CF-E4F248E5A97F}.Release|Any CPU.Build.0 = Release|Any CPU {8BE513ED-84F4-47E1-946D-84958CF95E6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8BE513ED-84F4-47E1-946D-84958CF95E6B}.Debug|Any CPU.Build.0 = Debug|Any CPU {8BE513ED-84F4-47E1-946D-84958CF95E6B}.Release|Any CPU.ActiveCfg = Release|Any CPU {8BE513ED-84F4-47E1-946D-84958CF95E6B}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {78214390-EFBD-403C-8AAA-5CD4CA5AE2ED} EndGlobalSection EndGlobal ================================================ FILE: README.md ================================================ # MongoDbGenericRepository An example of generic repository implementation using the MongoDB C# Sharp 2.0 (and now 3.*) driver (async) Now available as a nuget package: https://www.nuget.org/packages/MongoDbGenericRepository/ Covered by 400+ integration tests and counting. The MongoDbGenericRepository is also used in [AspNetCore.Identity.MongoDbCore](https://github.com/alexandre-spieser/AspNetCore.Identity.MongoDbCore). # Support This Project If you have found this project helpful, either as a library that you use or as a learning tool, please consider buying Alex a coffee: Buy Me A Coffee # Worth Knowing This package sets the `MongoDefaults.GuidRepresentation` to `MongoDB.Bson.GuidRepresentation.Standard` by default, instead of the default driver setting of `MongoDB.Bson.GuidRepresentation.CSharpLegacy`. This can cause issues if you have been using the driver on an existing application previously or if you are using CosmosDB. You can override this behaviour to enforce legacy behaviour in your app Startup routine like so : `MongoDbContext.SetGuidRepresentation(MongoDB.Bson.GuidRepresentation.CSharpLegacy)`. More info [here](https://github.com/alexandre-spieser/mongodb-generic-repository/issues/7). # Usage examples This repository is meant to be inherited from. You are responsible for managing its lifetime, it is advised to setup this repository as a singleton. Here is an example of repository usage, where the TestRepository is implementing 2 custom methods: ```csharp public interface ITestRepository : IBaseMongoRepository { void DropTestCollection(); void DropTestCollection(string partitionKey); } public class TestRepository : BaseMongoRepository, ITestRepository { public TestRepository(string connectionString, string databaseName) : base(connectionString, databaseName) { } public void DropTestCollection() { MongoDbContext.DropCollection(); } public void DropTestCollection(string partitionKey) { MongoDbContext.DropCollection(partitionKey); } } ``` If all your documents have the same type of `Id`, you can use the more specific `BaseMongoRepository` where `TKey` is the type of the `Id` of your documents. ```csharp public class TestTKeyRepository : BaseMongoRepository, ITestRepository where TKey : IEquatable { const string connectionString = "mongodb://localhost:27017/MongoDbTests"; private static readonly ITestRepository _instance = new TestTKeyRepository(connectionString); /// private TestTKeyRepository(string connectionString) : base(connectionString) { } } ``` ## Instantiation The repository can be instantiated like so: ```csharp ITestRepository testRepository = new TestRepository(connectionString, "MongoDbTests"); ITestRepository testTKeyRepository = new TestTKeyRepository(connectionString); ``` If you prefer to reuse the same MongoDb database across your application, you can use the `MongoDatabase` from the MongoDb driver implementing the `IMongoDatabase` interface: ```csharp var client = new MongoClient(connectionString); var mongoDbDatabase = Client.GetDatabase(databaseName); ITestRepository testRepository = new TestRepository(mongoDbDatabase); ``` ## Adding documents To add a document, its class must inherit from the `Document` class, implement the `IDocument` or `IDocument` interface: ```csharp public class MyDocument : Document { public MyDocument() { Version = 2; // you can bump the version of the document schema if you change it over time } public string SomeContent { get; set; } } ``` The `IDocument` and `IDocument` interfaces can be seen below: ```csharp /// /// This class represents a basic document that can be stored in MongoDb. /// Your document must implement this class in order for the MongoDbRepository to handle them. /// public interface IDocument { Guid Id { get; set; } int Version { get; set; } } /// /// This class represents a basic document that can be stored in MongoDb. /// Your document must implement this class in order for the MongoDbRepository to handle them. /// public interface IDocument where TKey : IEquatable { /// /// The Primary Key, which must be decorated with the [BsonId] attribute /// if you want the MongoDb C# driver to consider it to be the document ID. /// [BsonId] TKey Id { get; set; } /// /// A version number, to indicate the version of the schema. /// int Version { get; set; } } ``` ## Partitioned collections This repository also allows you to partition your document across multiple collections, this can be useful if you are running a SaaS application and want to keep good performance. To use partitioned collections, you must define your documents using the PartitionedDocument class, which implements the IPartitionedDocument interface: ```csharp public class MyPartitionedDocument : PartitionedDocument { public MyPartitionedDocument(string myPartitionKey) : base(myPartitionKey) { Version = 1; } public string SomeContent { get; set; } } ``` This partitioned key will be used as a prefix to your collection name. The collection name is derived from the name of the type of your document, is set to camel case, and is pluralized using a class taken from Humanizer (https://github.com/Humanizr/Humanizer). ```csharp var myDoc = new MyPartitionedDocument("myPartitionKey"); _testRepository.AddOne(myDoc); ``` The above code will generate a collection named `myPartitionKey-myPartitionedDocuments`. ## CollectionName Attribute It is now possible to change the collection name by using the `CollectionName` attribute: ```csharp [CollectionName("MyCollectionName")] public class MyDocument : Document { public MyDocument() { Version = 2; } public string SomeContent { get; set; } } ``` Documents of this type will be inserted into a collection named "MyCollectionName". ## Index Management From version 1.3.8 the `MongoDbGenericRepository` implements the `IBaseMongoRepository_Index` and `IBaseMongoRepository_Index` interfaces. This exposes the functionality to programmatically manage indexes against your collections in a generic fashion. The following methods are exposed and fully integration tested: + CreateAscendingIndexAsync + CreateDescendingIndexAsync + CreateCombinedTextIndexAsync + CreateHashedIndexAsync + CreateTextIndexAsync + DropIndexAsync + GetIndexesNamesAsync Usage examples: ```csharp string expectedIndexName = $"myCustomIndexName"; var option = new IndexCreationOptions { Name = expectedIndexName }; // Act // create a text index against the Version property of the document. var result = await SUT.CreateTextIndexAsync(x => x.Version, option, PartitionKey); // Assert var listOfIndexNames = await SUT.GetIndexesNamesAsync(PartitionKey); Assert.Contains(expectedIndexName, listOfIndexNames); // Cleanup await SUT.DropIndexAsync(expectedIndexName, PartitionKey); ``` Please refer to the IntegrationTests (NET45) and CoreIntegrationTests (netstandard2.0) projects for more usage examples. The `CoreIntegrationTests.Infrastructure.MongoDbTKeyDocumentTestBase` test class is a good start. ## Author **Alexandre Spieser** ## License mongodb-generic-repository is under MIT license - http://www.opensource.org/licenses/mit-license.php The MIT License (MIT) Copyright (c) 2016-2019 Alexandre Spieser Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================== Inflector (https://github.com/srkirkland/Inflector) The MIT License (MIT) Copyright (c) 2013 Scott Kirkland ============================================================================== Humanizer (https://github.com/Humanizr/Humanizer) The MIT License (MIT) Copyright (c) 2012-2014 Mehdi Khalili (http://omar.io) ============================================================================== ## Copyright Copyright © 2019