Compare commits

..

64 Commits

Author SHA1 Message Date
alexandre-spieser e41a73f745 1.3.7 release 2018-09-09 18:55:53 +01:00
alexandre-spieser 526adf0a23 remove unused using statements 2018-09-09 13:31:42 +01:00
alexandre-spieser db4061dc3c cleanup. Removing redundant GetCollection and Drop collection method, removed static constructor, added a virtual initialization method. 2018-09-09 13:05:45 +01:00
alexandre-spieser 72ea6e7999 clean up + full support for bulk insertion and deletion of documents of the same type but with different partitionkey values 2018-09-09 12:14:43 +01:00
alexandre-spieser 7f126a098d support insertion of documents with different PartitionKey values 2018-09-03 21:46:30 +01:00
alexandre-spieser 456af09a84 + Upgraded packages
+ Added GetByMax, GetByMaxAsync, GetByMin, GetByMinAsync, GetMaxValue and GetMaxValueAsync Methods (GetMinValue and GetMinValueAsync will come in another PR)
+ Added tests
2018-08-05 21:10:41 +01:00
Alexandre SPIESER f0af32adca Update copyright year to 2018 2018-05-11 22:53:43 +01:00
alexandre-spieser 345fca2e6e Added summary where needed. 2018-03-06 23:11:33 +00:00
alexandre-spieser 57d332ef2a Add support for ObjectId type for the Id of the document. 2018-03-05 23:07:56 +00:00
Alexandre SPIESER 2f6515a809 Merge pull request #3 from alexandre-spieser/add-license-1
Create LICENSE
2018-02-24 12:22:58 +00:00
Alexandre SPIESER 82dc2f2024 Create LICENSE 2018-02-24 12:22:49 +00:00
Alexandre SPIESER bc992e8c61 Update README.md 2018-02-16 15:11:09 +00:00
Alexandre SPIESER 47e85f1760 Update README.md 2018-02-16 15:10:18 +00:00
alexandre-spieser 6f5eb71dad Prepare for 1.3.5 release. 2018-02-10 18:32:45 +00:00
alexandre-spieser ed0d206a97 Merge branch 'master' of https://github.com/alexandre-spieser/mongodb-generic-repository 2018-02-10 18:17:42 +00:00
alexandre-spieser 40ff874cf6 CoreIntegrationTests refactored and passing. 2018-02-10 18:16:14 +00:00
alexandre-spieser 9fc74fc28e cleanup redundant tests. 2018-02-10 16:46:59 +00:00
alexandre-spieser 5270271008 Continues refactoring tests, added overload for UpdateOne and UpdateOneAsync so that we can pass a LINQ query to the method. 2018-02-10 16:38:47 +00:00
alexandre-spieser bf2119432e Test refactoring, continued. 2018-02-10 14:13:10 +00:00
Alexandre SPIESER e581586161 Update README.md 2018-02-07 12:59:13 +00:00
alexandre-spieser 1a83abd25f refactoring test classes. 2018-02-05 23:48:11 +00:00
Alexandre SPIESER 03b0e4265b Merge pull request #2 from Etchelon/master
Add CollectionName attribute for allowing explicit naming of collections
2018-02-05 20:32:50 +00:00
Andrea Bertoldo c117bf2a7f Add CollectionName attribute for allowing explicit naming of collections 2018-02-05 14:48:26 +01:00
Alexandre SPIESER c50e4d086e Update README.md 2018-01-27 16:44:03 +00:00
alexandre-spieser 3a42a1c574 Upgraded mongodb driver + new package version released. 2018-01-27 15:58:16 +00:00
alexandre-spieser 67e7318021 updating mongodb driver to version 2.5.0 for MongoDB 3.6 support. 2018-01-27 14:49:13 +00:00
alexandre-spieser 29012d1e52 nuget package update 2018-01-27 14:41:39 +00:00
alexandre-spieser e15c1e4ad2 Refactoring to have a greater separation of concern. 2017-12-06 23:20:53 +00:00
alexandre-spieser 3d104764ae added dependencies 2017-11-19 19:05:22 +00:00
alexandre-spieser 3af68c06db Merge branch 'master' of https://github.com/alexandre-spieser/mongodb-generic-repository 2017-11-17 18:39:38 +00:00
alexandre-spieser a3ae98d077 added comments and updated nuspec 2017-11-17 18:39:34 +00:00
Alexandre SPIESER aff276f9e3 Update README.md 2017-11-16 17:14:40 +00:00
Alexandre SPIESER e91c89f054 Update README.md 2017-11-01 08:27:59 +00:00
alexandre-spieser 657beeac99 The MongoDbRepository now has a constructor that takes an IMongoDatabase. 2017-11-01 08:18:29 +00:00
alexandre-spieser fbb07475a1 Added tests for IdentityUsers 2017-10-29 19:29:43 +00:00
Alexandre SPIESER 30ea910b9c Update README.md 2017-10-22 01:06:26 +01:00
Alexandre SPIESER aae71cddc3 Update README.md 2017-10-02 00:20:50 +01:00
Alexandre SPIESER ad2cd66a7d Update README.md 2017-10-01 22:47:37 +01:00
alexandre-spieser bfe1652b9c Merge branch 'AddingTKey' 2017-10-01 22:36:05 +00:00
alexandre-spieser 9c0cd0fe47 dll added. 2017-10-01 22:35:51 +00:00
alexandre-spieser c07b1a5d7b Added grouping functionality and tests. 2017-10-01 22:30:30 +00:00
alexandre-spieser 76862b2caa new nuget package 2017-09-25 22:40:00 +00:00
alexandre-spieser a13800637f added more tests for the documents implementing the IDocument<TKey> interface 2017-09-25 21:44:10 +00:00
alexandre-spieser 1d985e0274 Added tests 2017-09-24 21:34:29 +00:00
Alexandre SPIESER 833263edbf Update README.md 2017-09-24 20:04:15 +01:00
alexandre-spieser 6552a01d28 TKey support, continued 2017-09-23 22:32:44 +00:00
alexandre-spieser 9b1048e318 Adding TKey support 2017-09-23 22:00:31 +00:00
alexandre-spieser 5e187e0b1f Exposed core MongoDb driver objects and removed the AddedAtUtc property constraint from the IDocument interface. 2017-09-23 18:57:56 +00:00
Alexandre SPIESER b843f2de7f Update README.md 2017-09-18 14:54:57 +01:00
Alexandre SPIESER 90ba1e4fc6 Update README.md 2017-09-10 13:07:22 +01:00
Alexandre SPIESER 926099626d Update README.md 2017-09-10 13:06:39 +01:00
alexandre-spieser 58cf1f1faf Generated nuget package 1.2 and tests passing. 2017-09-09 19:13:32 +00:00
alexandre-spieser 39879f6f5f removed the unused configuration manager package 2017-09-09 17:53:52 +00:00
alexandre-spieser 54efe5e520 .NET Core tests with xunit 2017-09-09 17:52:12 +00:00
alexandre-spieser fb4ee42a5c now targeting multiple frameworks (net45 and netstandard1.5) 2017-09-09 16:52:10 +00:00
Alexandre SPIESER e55ff5796a Update README.md 2017-09-05 22:46:26 +01:00
alexandre-spieser 98b859938e Merge branch 'master' of https://github.com/alexandre-spieser/mongodb-generic-repository 2017-09-03 21:32:31 +00:00
alexandre-spieser bbadd78d1b pushing version up 2017-09-03 21:32:25 +00:00
alexandre-spieser 296dc6f7c5 Merge branch 'master' of https://github.com/alexandre-spieser/mongodb-generic-repository 2017-09-03 19:00:18 +00:00
alexandre-spieser b94b499c10 added pluralizationclass from Humanizer, and set collections names to camel case instead of lower case for better readability. 2017-09-03 19:00:02 +00:00
Alexandre SPIESER 8044ec8e56 Update README.md 2017-09-03 19:31:27 +01:00
Alexandre SPIESER 8fc45cd975 Update README.md 2017-09-03 19:25:01 +01:00
Alexandre SPIESER 5827b5de9a Update README.md 2017-09-03 19:07:58 +01:00
Alexandre SPIESER aae4e4e710 Update README.md 2017-09-03 18:03:56 +01:00
173 changed files with 19483 additions and 128073 deletions
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="MongoDbTests" connectionString="mongodb://localhost:27017" />
</connectionStrings>
</configuration>
+22
View File
@@ -0,0 +1,22 @@
using CoreIntegrationTests.Infrastructure;
using MongoDB.Bson;
using System;
namespace CoreIntegrationTests
{
public class CoreObjectIdTestDocument : TestDoc<ObjectId>
{
}
public class CRUDObjectIdTests : MongoDbTKeyDocumentTestBase<CoreObjectIdTestDocument, ObjectId>
{
public CRUDObjectIdTests(MongoDbTestFixture<CoreObjectIdTestDocument, ObjectId> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CRUDObjectIdTests";
}
}
}
@@ -0,0 +1,31 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Attributes;
using MongoDbGenericRepository.Models;
using System;
namespace CoreIntegrationTests
{
[CollectionName("CoreTestingCollectionNameAttributePartitionedTKey")]
public class CorePartitionedCollectionNameDoc : TestDoc, IPartitionedDocument
{
public CorePartitionedCollectionNameDoc()
{
PartitionKey = "CoreTestPartitionKeyCollectionName";
}
public string PartitionKey { get; set; }
}
public class CRUDPartitionedCollectionNameAttributeTests : MongoDbDocumentTestBase<CorePartitionedCollectionNameDoc>
{
public CRUDPartitionedCollectionNameAttributeTests(MongoDbTestFixture<CorePartitionedCollectionNameDoc, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CoreCRUDPartitionedCollectionNameAttributeTests";
}
}
}
@@ -0,0 +1,28 @@
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<CorePartitionedDoc>
{
public CRUDPartitionedTests(MongoDbTestFixture<CorePartitionedDoc, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CoreCRUDPartitionedTests";
}
}
}
@@ -0,0 +1,31 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Attributes;
using MongoDbGenericRepository.Models;
using System;
namespace CoreIntegrationTests
{
[CollectionName("TestingCollectionNameAttributePartitionedTKey")]
public class CoreTKeyPartitionedCollectionNameDoc : TestDoc<Guid>, IPartitionedDocument
{
public CoreTKeyPartitionedCollectionNameDoc()
{
PartitionKey = "CoreTestPartitionKey";
}
public string PartitionKey { get; set; }
}
public class CRUDTKeyPartitionedCollectionNameAttributeTests : MongoDbTKeyDocumentTestBase<CoreTKeyPartitionedCollectionNameDoc, Guid>
{
public CRUDTKeyPartitionedCollectionNameAttributeTests(MongoDbTestFixture<CoreTKeyPartitionedCollectionNameDoc, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CoreCRUDTKeyPartitionedCollectionNameAttributeTests";
}
}
}
@@ -0,0 +1,28 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using System;
namespace CoreIntegrationTests
{
public class CorePartitionedTKeyTestDocument : TestDoc<Guid>, IPartitionedDocument
{
public CorePartitionedTKeyTestDocument()
{
PartitionKey = "CoreTestPartitionKey";
}
public string PartitionKey { get; set; }
}
public class CRUDTKeyPartitionedTests : MongoDbTKeyDocumentTestBase<CorePartitionedTKeyTestDocument, Guid>
{
public CRUDTKeyPartitionedTests(MongoDbTestFixture<CorePartitionedTKeyTestDocument, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CoreCRUDTKeyPartitionedTests";
}
}
}
+22
View File
@@ -0,0 +1,22 @@
using CoreIntegrationTests.Infrastructure;
using System;
namespace CoreIntegrationTests
{
public class CoreTKeyTestDocument : TestDoc<Guid>
{
}
public class CRUDTKeyTests : MongoDbTKeyDocumentTestBase<CoreTKeyTestDocument, Guid>
{
public CRUDTKeyTests(MongoDbTestFixture<CoreTKeyTestDocument, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CreateTKeyTests";
}
}
}
+22
View File
@@ -0,0 +1,22 @@
using CoreIntegrationTests.Infrastructure;
using System;
namespace CoreIntegrationTests
{
public class CoreTestDocument : TestDoc
{
}
public class CRUDTests : MongoDbDocumentTestBase<CoreTestDocument>
{
public CRUDTests(MongoDbTestFixture<CoreTestDocument, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CRUDTests";
}
}
}
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.1.2" />
<PackageReference Include="Microsoft.Extensions.Identity.Stores" Version="2.1.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
<PackageReference Include="MongoDB.Driver" Version="2.7.0" />
<PackageReference Include="MongoDbGenericRepository" Version="1.3.7" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.console" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.0-beta4-build3742" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Configuration">
<HintPath>..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Configuration.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<None Update="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+77
View File
@@ -0,0 +1,77 @@
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<TKey> : IdentityUser<TKey>, IDocument<TKey>
where TKey : IEquatable<TKey>
{
public int Version { get; set; }
}
public class IdentityUserTest : MongoIdentityUser<Guid>, IDocument<Guid>
{
public IdentityUserTest()
{
Id = Guid.NewGuid();
Version = 2;
}
public string SomeContent { get; set; }
}
public class IdentityUserTests : BaseMongoDbRepositoryTests<IdentityUserTest>
{
[Fact]
public void AddOne()
{
// Arrange
var document = new IdentityUserTest();
// Act
SUT.AddOne<IdentityUserTest, Guid>(document);
// Assert
long count = SUT.Count<IdentityUserTest, Guid>(e => e.Id == document.Id);
Assert.Equal(1, count);
}
[Fact]
public async Task AddOneAsync()
{
// Arrange
var document = new IdentityUserTest();
// Act
await SUT.AddOneAsync<IdentityUserTest, Guid>(document);
// Assert
long count = SUT.Count<IdentityUserTest, Guid>(e => e.Id == document.Id);
Assert.Equal(1, count);
}
[Fact]
public void AddMany()
{
// Arrange
var documents = new List<IdentityUserTest> { new IdentityUserTest(), new IdentityUserTest() };
// Act
SUT.AddMany<IdentityUserTest, Guid>(documents);
// Assert
long count = SUT.Count<IdentityUserTest, Guid>(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<IdentityUserTest> { new IdentityUserTest(), new IdentityUserTest() };
// Act
await SUT.AddManyAsync<IdentityUserTest, Guid>(documents);
// Assert
long count = SUT.Count<IdentityUserTest, Guid>(e => e.Id == documents[0].Id || e.Id == documents[1].Id);
Assert.Equal(2, count);
}
}
}
@@ -0,0 +1,88 @@
using MongoDbGenericRepository.Models;
using System.Collections.Generic;
using System;
namespace CoreIntegrationTests.Infrastructure
{
public class BaseMongoDbRepositoryTests<T> : IDisposable where T : new()
{
public T CreateTestDocument()
{
return new T();
}
public List<T> CreateTestDocuments(int numberOfDocumentsToCreate)
{
var docs = new List<T>();
for(var i = 0; i < numberOfDocumentsToCreate; i++)
{
docs.Add(new T());
}
return docs;
}
/// <summary>
/// Constructor, init code
/// </summary>
public BaseMongoDbRepositoryTests()
{
Init();
var type = CreateTestDocument();
if (type is IPartitionedDocument)
{
PartitionKey = ((IPartitionedDocument)type).PartitionKey;
}
}
public string PartitionKey { get; set; }
/// <summary>
/// SUT: System Under Test
/// </summary>
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<T>(PartitionKey);
}
else
{
SUT.DropTestCollection<T>();
}
}
#region IDisposable Support
private bool disposedValue = false; // 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
}
}
@@ -0,0 +1,15 @@
using System;
namespace CoreIntegrationTests.Infrastructure
{
/// <summary>
/// A class holding global variables.
/// </summary>
public static class GlobalVariables
{
/// <summary>
/// A random number generator.
/// </summary>
public static Random Random = new Random();
}
}
@@ -0,0 +1,10 @@
using MongoDbGenericRepository;
namespace CoreIntegrationTests
{
public interface ITestRepository : IBaseMongoRepository
{
void DropTestCollection<TDocument>();
void DropTestCollection<TDocument>(string partitionKey);
}
}
@@ -0,0 +1,41 @@
using MongoDB.Bson.Serialization.Conventions;
using System.Threading;
namespace CoreIntegrationTests.Infrastructure
{
internal static class MongoDbConfig
{
private static bool _initialized = false;
private static object _initializationLock = new object();
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(),
};
}
}
}
@@ -0,0 +1,985 @@
using MongoDbGenericRepository.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
namespace CoreIntegrationTests.Infrastructure
{
public abstract class MongoDbDocumentTestBase<T> :
IClassFixture<MongoDbTestFixture<T, Guid>>
where T: TestDoc, new()
{
private readonly MongoDbTestFixture<T, Guid> _fixture;
protected MongoDbDocumentTestBase(MongoDbTestFixture<T, Guid> 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;
}
protected T CreateTestDocument()
{
return _fixture.CreateTestDocument();
}
public abstract string GetClassName();
protected List<T> CreateTestDocuments(int numberOfDocumentsToCreate)
{
return _fixture.CreateTestDocuments(numberOfDocumentsToCreate);
}
/// <summary>
/// The partition key for the collection, if any
/// </summary>
protected string PartitionKey { get; set; }
/// <summary>
/// the name of the test class
/// </summary>
protected string TestClassName { get; set; }
/// <summary>
/// The name of the document used for tests
/// </summary>
protected string DocumentTypeName { get; set; }
/// <summary>
/// SUT: System Under Test
/// </summary>
protected static ITestRepository SUT { get; set; }
#region Add
[Fact]
public void AddOne()
{
// Arrange
var document = new T();
// Act
SUT.AddOne<T>(document);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T>(e => e.Id.Equals(document.Id))
: SUT.Count<T>(e => e.Id.Equals(document.Id), PartitionKey);
Assert.True(1 == count, GetTestName());
}
[Fact]
public async Task AddOneAsync()
{
// Arrange
var document = new T();
// Act
await SUT.AddOneAsync<T>(document);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T>(e => e.Id.Equals(document.Id))
: SUT.Count<T>(e => e.Id.Equals(document.Id), PartitionKey);
Assert.True (1 == count, GetTestName());
}
[Fact]
public void AddMany()
{
// Arrange
var documents = new List<T> { new T(), new T() };
// Act
SUT.AddMany<T>(documents);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id))
: SUT.Count<T>(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 = new List<T> { new T(), new T(), new T(), new T() };
if(documents.Any(e => e is IPartitionedDocument))
{
var secondPartitionKey = $"{PartitionKey}-2";
((IPartitionedDocument)documents[2]).PartitionKey = secondPartitionKey;
((IPartitionedDocument)documents[3]).PartitionKey = secondPartitionKey;
// Act
SUT.AddMany<T>(documents);
// Assert
long count = SUT.Count<T>(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey);
long secondPartitionCount = SUT.Count<T>(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey);
// Cleanup second partition
SUT.DeleteMany<T>(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 = new List<T> { new T(), new T() };
// Act
await SUT.AddManyAsync<T>(documents);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id))
: SUT.Count<T>(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 = new List<T> { new T(), new T(), new T(), new T() };
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<T>(documents);
// Assert
long count = SUT.Count<T>(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey);
long secondPartitionCount = SUT.Count<T>(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey);
// Cleanup second partition
SUT.DeleteMany<T>(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<T>(document);
// Act
var result = await SUT.GetByIdAsync<T>(document.Id, PartitionKey);
// Assert
Assert.True(null != result, GetTestName());
}
[Fact]
public void GetById()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.GetById<T>(document.Id, PartitionKey);
// Assert
Assert.True(null != result, GetTestName());
}
[Fact]
public async Task GetOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.GetOneAsync<T>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True(null != result, GetTestName());
}
[Fact]
public void GetOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.GetOne<T>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True(null != result, GetTestName());
}
[Fact]
public void GetCursor()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var cursor = SUT.GetCursor<T>(x => x.Id.Equals(document.Id), PartitionKey);
var count = cursor.Count();
// Assert
Assert.True (1 == count, GetTestName());
}
[Fact]
public async Task AnyAsyncReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.AnyAsync<T>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True(result, GetTestName());
}
[Fact]
public async Task AnyAsyncReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.AnyAsync<T>(x => x.Id.Equals(Guid.NewGuid()), PartitionKey);
// Assert
Assert.False(result, GetTestName());
}
[Fact]
public void AnyReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.Any<T>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True(result, GetTestName());
}
[Fact]
public void AnyReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.Any<T>(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<T>(documents);
// Act
var result = await SUT.GetAllAsync<T>(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<T>(documents);
// Act
var result = SUT.GetAll<T>(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<T>(documents);
// Act
var result = await SUT.CountAsync<T>(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<T>(documents);
// Act
var result = SUT.Count<T>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.True(5 == result, GetTestName());
}
#endregion Read
#region Update
[Fact]
public void UpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = SUT.UpdateOne<T>(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T>(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<T>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = await SUT.UpdateOneAsync<T>(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public void UpdateOneField()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, string>(document, x => x.SomeContent, content);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T>(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<T>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, string>(document, x => x.SomeContent, content);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public void UpdateOneFieldWithFilter()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T>(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<T>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T>(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<T>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = await SUT.UpdateOneAsync<T>(document, updateDef);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T>(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<T>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = SUT.UpdateOne<T>(document, updateDef);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T>(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
#region Delete
[Fact]
public void DeleteOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.DeleteOne<T>(document);
// Assert
Assert.True (1 == result);
Assert.False(SUT.Any<T>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Fact]
public void DeleteOneLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.DeleteOne<T>(e => e.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True (1 == result);
Assert.False(SUT.Any<T>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Fact]
public async Task DeleteOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.DeleteOneAsync<T>(document);
// Assert
Assert.True (1 == result);
Assert.False(SUT.Any<T>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Fact]
public async Task DeleteOneAsyncLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.DeleteOneAsync<T>(e => e.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True (1 == result);
Assert.False(SUT.Any<T>(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<T>(documents);
// Act
var result = await SUT.DeleteManyAsync<T>(e => e.SomeContent == criteria, PartitionKey);
// Assert
Assert.True(5 == result);
Assert.False(SUT.Any<T>(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<T>(documents);
// Act
var result = await SUT.DeleteManyAsync<T>(documents);
// Assert
Assert.True(5 == result);
Assert.False(SUT.Any<T>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
if (canPartition)
{
Assert.False(SUT.Any<T>(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<T>(documents);
// Act
var result = SUT.DeleteMany<T>(e => e.SomeContent == criteria, PartitionKey);
// Assert
Assert.True(5 == result);
Assert.False(SUT.Any<T>(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<T>(documents);
// Act
var result = SUT.DeleteMany<T>(documents);
// Assert
Assert.True(5 == result);
Assert.False(SUT.Any<T>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
if (canPartition)
{
Assert.False(SUT.Any<T>(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<T>(document);
// Act
var result = await SUT.ProjectOneAsync<T, MyTestProjection>(
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<T>(document);
// Act
var result = SUT.ProjectOne<T, MyTestProjection>(
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<T>(documents);
// Act
var result = await SUT.ProjectManyAsync<T, MyTestProjection>(
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<T>(documents);
// Act
var result = SUT.ProjectMany<T, MyTestProjection>(
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<T>(documents);
var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First();
// Act
var result = await SUT.GetByMaxAsync<T>(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<T>(documents);
var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First();
// Act
var result = SUT.GetByMax<T>(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<T>(documents);
var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First();
// Act
var result = await SUT.GetByMinAsync<T>(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<T>(documents);
var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First();
// Act
var result = SUT.GetByMin<T>(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<T>(documents);
var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First();
// Act
var result = SUT.GetMinValue<T, DateTime>(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<T>(documents);
var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First();
// Act
var result = await SUT.GetMinValueAsync<T, DateTime>(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<T>(documents);
var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First();
// Act
var result = SUT.GetMaxValue<T, DateTime>(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<T>(documents);
var expectedMin = documents.OrderByDescending(e => e.Nested.SomeDate).First();
// Act
var result = await SUT.GetMaxValueAsync<T, DateTime>(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 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<T>(PartitionKey);
}
else
{
SUT.DropTestCollection<T>();
}
}
#endregion Test Utils
}
}
@@ -0,0 +1,985 @@
using MongoDbGenericRepository.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
namespace CoreIntegrationTests.Infrastructure
{
public abstract class MongoDbTKeyDocumentTestBase<T, TKey> :
IClassFixture<MongoDbTestFixture<T, TKey>>
where T: TestDoc<TKey>, new()
where TKey : IEquatable<TKey>
{
private readonly MongoDbTestFixture<T, TKey> _fixture;
protected MongoDbTKeyDocumentTestBase(MongoDbTestFixture<T, TKey> 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<T> CreateTestDocuments(int numberOfDocumentsToCreate)
{
return _fixture.CreateTestDocuments(numberOfDocumentsToCreate);
}
/// <summary>
/// The partition key for the collection, if any
/// </summary>
protected string PartitionKey { get; set; }
/// <summary>
/// the name of the test class
/// </summary>
protected string TestClassName { get; set; }
/// <summary>
/// The name of the document used for tests
/// </summary>
protected string DocumentTypeName { get; set; }
/// <summary>
/// SUT: System Under Test
/// </summary>
protected static ITestRepository SUT { get; set; }
#region Add
[Fact]
public void AddOne()
{
// Arrange
var document = new T();
// Act
SUT.AddOne<T, TKey>(document);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T, TKey>(e => e.Id.Equals(document.Id))
: SUT.Count<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey);
Assert.True(1 == count, GetTestName());
}
[Fact]
public async Task AddOneAsync()
{
// Arrange
var document = new T();
// Act
await SUT.AddOneAsync<T, TKey>(document);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T, TKey>(e => e.Id.Equals(document.Id))
: SUT.Count<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey);
Assert.True (1 == count, GetTestName());
}
[Fact]
public void AddMany()
{
// Arrange
var documents = new List<T> { new T(), new T() };
// Act
SUT.AddMany<T, TKey>(documents);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T, TKey>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id))
: SUT.Count<T, TKey>(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 = new List<T> { new T(), new T(), new T(), new T() };
if (documents.Any(e => e is IPartitionedDocument))
{
var secondPartitionKey = $"{PartitionKey}-2";
((IPartitionedDocument)documents[2]).PartitionKey = secondPartitionKey;
((IPartitionedDocument)documents[3]).PartitionKey = secondPartitionKey;
// Act
SUT.AddMany<T, TKey>(documents);
// Assert
long count = SUT.Count<T, TKey>(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey);
long secondPartitionCount = SUT.Count<T, TKey>(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey);
// Cleanup second partition
SUT.DeleteMany<T, TKey>(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 = new List<T> { new T(), new T() };
// Act
await SUT.AddManyAsync<T, TKey>(documents);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T, TKey>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id))
: SUT.Count<T, TKey>(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 = new List<T> { new T(), new T(), new T(), new T() };
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<T, TKey>(documents);
// Assert
long count = SUT.Count<T, TKey>(e => e.Id.Equals(documents[0].Id) || e.Id.Equals(documents[1].Id), PartitionKey);
long secondPartitionCount = SUT.Count<T, TKey>(e => e.Id.Equals(documents[2].Id) || e.Id.Equals(documents[3].Id), secondPartitionKey);
// Cleanup second partition
SUT.DeleteMany<T, TKey>(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<T, TKey>(document);
// Act
var result = await SUT.GetByIdAsync<T, TKey>(document.Id, PartitionKey);
// Assert
Assert.True(null != result, GetTestName());
}
[Fact]
public void GetById()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.GetById<T, TKey>(document.Id, PartitionKey);
// Assert
Assert.True(null != result, GetTestName());
}
[Fact]
public async Task GetOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.GetOneAsync<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True(null != result, GetTestName());
}
[Fact]
public void GetOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.GetOne<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True(null != result, GetTestName());
}
[Fact]
public void GetCursor()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var cursor = SUT.GetCursor<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
var count = cursor.Count();
// Assert
Assert.True (1 == count, GetTestName());
}
[Fact]
public async Task AnyAsyncReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.AnyAsync<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True(result, GetTestName());
}
[Fact]
public async Task AnyAsyncReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.AnyAsync<T, TKey>(x => x.Id.Equals(document.Init<TKey>()), PartitionKey);
// Assert
Assert.False(result, GetTestName());
}
[Fact]
public void AnyReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.Any<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True(result, GetTestName());
}
[Fact]
public void AnyReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.Any<T, TKey>(x => x.Id.Equals(document.Init<TKey>()), 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<T, TKey>(documents);
// Act
var result = await SUT.GetAllAsync<T, TKey>(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<T, TKey>(documents);
// Act
var result = SUT.GetAll<T, TKey>(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<T, TKey>(documents);
// Act
var result = await SUT.CountAsync<T, TKey>(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<T, TKey>(documents);
// Act
var result = SUT.Count<T, TKey>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.True(5 == result, GetTestName());
}
#endregion Read
#region Update
[Fact]
public void UpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = SUT.UpdateOne<T, TKey>(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T, TKey>(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<T, TKey>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = await SUT.UpdateOneAsync<T, TKey>(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public void UpdateOneField()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, TKey, string>(document, x => x.SomeContent, content);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(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<T, TKey>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, TKey, string>(document, x => x.SomeContent, content);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public void UpdateOneFieldWithFilter()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, TKey, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(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<T, TKey>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, TKey, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(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<T, TKey>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = await SUT.UpdateOneAsync<T, TKey>(document, updateDef);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T, TKey>(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<T, TKey>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = SUT.UpdateOne<T, TKey>(document, updateDef);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T, TKey>(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
#region Delete
[Fact]
public void DeleteOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.DeleteOne<T, TKey>(document);
// Assert
Assert.True (1 == result);
Assert.False(SUT.Any<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Fact]
public void DeleteOneLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.DeleteOne<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True (1 == result);
Assert.False(SUT.Any<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Fact]
public async Task DeleteOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.DeleteOneAsync<T, TKey>(document);
// Assert
Assert.True (1 == result);
Assert.False(SUT.Any<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Fact]
public async Task DeleteOneAsyncLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.DeleteOneAsync<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.True (1 == result);
Assert.False(SUT.Any<T, TKey>(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<T, TKey>(documents);
// Act
var result = await SUT.DeleteManyAsync<T, TKey>(e => e.SomeContent == criteria, PartitionKey);
// Assert
Assert.True(5 == result);
Assert.False(SUT.Any<T, TKey>(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<T, TKey>(documents);
// Act
var result = await SUT.DeleteManyAsync<T, TKey>(documents);
// Assert
Assert.True(5 == result);
Assert.False(SUT.Any<T, TKey>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
if (canPartition)
{
Assert.False(SUT.Any<T, TKey>(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<T, TKey>(documents);
// Act
var result = SUT.DeleteMany<T, TKey>(e => e.SomeContent == criteria, PartitionKey);
// Assert
Assert.True(5 == result);
Assert.False(SUT.Any<T, TKey>(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<T, TKey>(documents);
// Act
var result = SUT.DeleteMany<T, TKey>(documents);
// Assert
Assert.True(5 == result);
Assert.False(SUT.Any<T, TKey>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
if (canPartition)
{
Assert.False(SUT.Any<T, TKey>(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<T, TKey>(document);
// Act
var result = await SUT.ProjectOneAsync<T, MyTestProjection, TKey>(
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<T, TKey>(document);
// Act
var result = SUT.ProjectOne<T, MyTestProjection, TKey>(
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<T, TKey>(documents);
// Act
var result = await SUT.ProjectManyAsync<T, MyTestProjection, TKey>(
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<T, TKey>(documents);
// Act
var result = SUT.ProjectMany<T, MyTestProjection, TKey>(
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<T, TKey>(documents);
var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First();
// Act
var result = await SUT.GetByMaxAsync<T, TKey>(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<T, TKey>(documents);
var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First();
// Act
var result = SUT.GetByMax<T, TKey>(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<T, TKey>(documents);
var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First();
// Act
var result = SUT.GetMaxValue<T, TKey, DateTime>(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<T, TKey>(documents);
var expectedMax = documents.OrderByDescending(e => e.Nested.SomeDate).First();
// Act
var result = await SUT.GetMaxValueAsync<T, TKey, DateTime>(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<T, TKey>(documents);
var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First();
// Act
var result = await SUT.GetByMinAsync<T, TKey>(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<T, TKey>(documents);
var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First();
// Act
var result = SUT.GetByMin<T, TKey>(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<T, TKey>(documents);
var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First();
// Act
var result = SUT.GetMinValue< T, TKey, DateTime >(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<T, TKey>(documents);
var expectedMin = documents.OrderBy(e => e.Nested.SomeDate).First();
// Act
var result = await SUT.GetMinValueAsync< T, TKey, DateTime >(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 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<T>(PartitionKey);
}
else
{
SUT.DropTestCollection<T>();
}
}
#endregion Test Utils
}
}
@@ -0,0 +1,55 @@
using MongoDbGenericRepository;
using MongoDbGenericRepository.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace CoreIntegrationTests.Infrastructure
{
public class MongoDbTestFixture<T, TKey> : IDisposable
where T : IDocument<TKey>, new()
where TKey : IEquatable<TKey>
{
public IMongoDbContext Context;
public MongoDbTestFixture()
{
DocsToDelete = new ConcurrentBag<T>();
}
public string PartitionKey { get; set; }
public ConcurrentBag<T> DocsToDelete { get; set; }
public virtual void Dispose()
{
var docIds = DocsToDelete.ToList().Select(e => e.Id);
if (docIds.Any())
{
TestRepository.Instance.DeleteMany<T, TKey>(e => docIds.Contains(e.Id));
}
}
public T CreateTestDocument()
{
var doc = new T();
DocsToDelete.Add(doc);
return doc;
}
public List<T> CreateTestDocuments(int numberOfDocumentsToCreate)
{
var docs = new List<T>();
for (var i = 0; i < numberOfDocumentsToCreate; i++)
{
docs.Add(new T());
DocsToDelete.Add(docs.Last());
}
return docs;
}
}
}
@@ -0,0 +1,61 @@
using System;
namespace CoreIntegrationTests.Infrastructure
{
// Thanks BlueRaja - Danny Pflughoeft https://stackoverflow.com/a/13095144/5103354
/// <summary>
/// Extensions for the random number generator <see cref="Random"/>
/// </summary>
public static class RandomExtensions
{
/// <summary>
/// Returns a random long from min (inclusive) to max (exclusive)
/// </summary>
/// <param name="random">The given random instance</param>
/// <param name="min">The inclusive minimum bound</param>
/// <param name="max">The exclusive maximum bound. Must be greater than min</param>
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;
}
/// <summary>
/// Returns a random long from 0 (inclusive) to max (exclusive)
/// </summary>
/// <param name="random">The given random instance</param>
/// <param name="max">The exclusive maximum bound. Must be greater than 0</param>
public static long NextLong(this Random random, long max)
{
return random.NextLong(0, max);
}
/// <summary>
/// Returns a random long over all possible values of long (except long.MaxValue, similar to
/// random.Next())
/// </summary>
/// <param name="random">The given random instance</param>
public static long NextLong(this Random random)
{
return random.NextLong(long.MinValue, long.MaxValue);
}
}
}
@@ -0,0 +1,96 @@
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<string> 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<Child>();
}
public int SomeValue { get; set; }
public string SomeContent { get; set; }
public int GroupingKey { get; set; }
public Nested Nested { get; set; }
public List<Child> Children { get; set; }
}
public class TestDoc<TKey> : IDocument<TKey>
where TKey : IEquatable<TKey>
{
[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<Child>();
}
public string SomeContent { get; set; }
public Nested Nested { get; set; }
public List<Child> Children { get; set; }
public TId Init<TId>()
{
return IdGenerator.GetId<TId>();
}
private void InitializeFields()
{
Id = Init<TKey>();
}
}
}
@@ -0,0 +1,43 @@
using MongoDbGenericRepository;
namespace CoreIntegrationTests.Infrastructure
{
/// <summary>
/// A singleton implementation of the TestRepository
/// </summary>
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()
{
}
/// <inheritdoc />
private TestRepository(string connectionString, string databaseName) : base(connectionString, databaseName)
{
}
public static ITestRepository Instance
{
get
{
return _instance;
}
}
public void DropTestCollection<TDocument>()
{
MongoDbContext.DropCollection<TDocument>();
}
public void DropTestCollection<TDocument>(string partitionKey)
{
MongoDbContext.DropCollection<TDocument>(partitionKey);
}
}
}
+5 -1
View File
@@ -11,7 +11,11 @@
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
+19
View File
@@ -0,0 +1,19 @@
using IntegrationTests.Infrastructure;
using MongoDB.Bson;
using NUnit.Framework;
namespace IntegrationTests
{
public class ObjectIdTestDocument : TestDoc<ObjectId>
{
}
[TestFixture]
public class CRUDObjectIdTests : MongoDbTKeyDocumentTestBase<ObjectIdTestDocument, ObjectId>
{
public override string GetClassName()
{
return "CRUDObjectIdTests";
}
}
}
@@ -0,0 +1,27 @@
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<PartitionedCollectionNameDoc>
{
public override string GetClassName()
{
return "CRUDPartitionedCollectionNameAttributeTests";
}
}
}
+23
View File
@@ -0,0 +1,23 @@
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<PartitionedDoc>
{
public override string GetClassName()
{
return "CRUDPartitionedCollectionNameAttributeTests";
}
}
}
@@ -0,0 +1,26 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Attributes;
using MongoDbGenericRepository.Models;
using System;
namespace IntegrationTests
{
[CollectionName("TestingCollectionNameAttributePartitionedTKey")]
public class TKeyPartitionedCollectionNameDoc : TestDoc<Guid>, IPartitionedDocument
{
public TKeyPartitionedCollectionNameDoc()
{
PartitionKey = "TestPartitionKey";
}
public string PartitionKey { get; set; }
}
public class CRUDTKeyPartitionedCollectionNameAttributeTests : MongoDbTKeyDocumentTestBase<TKeyPartitionedCollectionNameDoc, Guid>
{
public override string GetClassName()
{
return "CRUDTKeyPartitionedCollectionNameAttributeTests";
}
}
}
@@ -0,0 +1,26 @@
using IntegrationTests.Infrastructure;
using MongoDB.Bson.Serialization.Attributes;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System;
namespace IntegrationTests
{
public class PartitionedTKeyTestDocument : TestDoc<Guid>, IPartitionedDocument
{
public PartitionedTKeyTestDocument()
{
PartitionKey = "TestPartitionKey";
}
public string PartitionKey { get; set; }
}
[TestFixture]
public class CRUDTKeyPartitionedTests : MongoDbTKeyDocumentTestBase<PartitionedTKeyTestDocument, Guid>
{
public override string GetClassName()
{
return "CRUDTKeyPartitionedTests";
}
}
}
+21
View File
@@ -0,0 +1,21 @@
using IntegrationTests.Infrastructure;
using MongoDB.Bson.Serialization.Attributes;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System;
namespace IntegrationTests
{
public class TKeyTestDocument : TestDoc<Guid>
{
}
[TestFixture]
public class CRUDTKeyTests : MongoDbTKeyDocumentTestBase<TKeyTestDocument, Guid>
{
public override string GetClassName()
{
return "CreateTKeyTests";
}
}
}
+18
View File
@@ -0,0 +1,18 @@
using IntegrationTests.Infrastructure;
using NUnit.Framework;
namespace IntegrationTests
{
public class TestDocument : TestDoc
{
}
[TestFixture]
public class CRUDTests : MongoDbDocumentTestBase<TestDocument>
{
public override string GetClassName()
{
return "CRUDTests";
}
}
}
@@ -1,68 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class CreateTestsPartitionedDocument : PartitionedDocument
{
public CreateTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 1;
}
public string SomeContent { get; set; }
}
public class CreatePartitionedTests : BaseMongoDbRepositoryTests<CreateTestsPartitionedDocument>
{
[Test]
public void PartitionedAddOne()
{
// Arrange
var document = new CreateTestsPartitionedDocument();
// Act
SUT.AddOne(document);
// Assert
long count = SUT.Count<CreateTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey);
Assert.AreEqual(1, count);
}
[Test]
public async Task PartitionedAddOneAsync()
{
// Arrange
var document = new CreateTestsPartitionedDocument();
// Act
await SUT.AddOneAsync(document);
// Assert
long count = SUT.Count<CreateTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey);
Assert.AreEqual(1, count);
}
[Test]
public void PartitionedAddMany()
{
// Arrange
var documents = new List<CreateTestsPartitionedDocument> { new CreateTestsPartitionedDocument(), new CreateTestsPartitionedDocument() };
// Act
SUT.AddMany(documents);
// Assert
long count = SUT.Count<CreateTestsPartitionedDocument>(e => e.Id == documents[0].Id || e.Id == documents[1].Id, PartitionKey);
Assert.AreEqual(2, count);
}
[Test]
public async Task PartitionedAddManyAsync()
{
// Arrange
var documents = new List<CreateTestsPartitionedDocument> { new CreateTestsPartitionedDocument(), new CreateTestsPartitionedDocument() };
// Act
await SUT.AddManyAsync(documents);
// Assert
long count = SUT.Count<CreateTestsPartitionedDocument>(e => e.Id == documents[0].Id || e.Id == documents[1].Id, PartitionKey);
Assert.AreEqual(2, count);
}
}
}
-69
View File
@@ -1,69 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class CreateTestsDocument : Document
{
public CreateTestsDocument()
{
Version = 2;
}
public string SomeContent { get; set; }
}
[TestFixture]
public class CreateTests : BaseMongoDbRepositoryTests<CreateTestsDocument>
{
[Test]
public void AddOne()
{
// Arrange
var document = new CreateTestsDocument();
// Act
SUT.AddOne(document);
// Assert
long count = SUT.Count<CreateTestsDocument>(e => e.Id == document.Id);
Assert.AreEqual(1, count);
}
[Test]
public async Task AddOneAsync()
{
// Arrange
var document = new CreateTestsDocument();
// Act
await SUT.AddOneAsync(document);
// Assert
long count = SUT.Count<CreateTestsDocument>(e => e.Id == document.Id);
Assert.AreEqual(1, count);
}
[Test]
public void AddMany()
{
// Arrange
var documents = new List<CreateTestsDocument> { new CreateTestsDocument(), new CreateTestsDocument() };
// Act
SUT.AddMany(documents);
// Assert
long count = SUT.Count<CreateTestsDocument>(e => e.Id == documents[0].Id || e.Id == documents[1].Id);
Assert.AreEqual(2, count);
}
[Test]
public async Task AddManyAsync()
{
// Arrange
var documents = new List<CreateTestsDocument> { new CreateTestsDocument(), new CreateTestsDocument() };
// Act
await SUT.AddManyAsync(documents);
// Assert
long count = SUT.Count<CreateTestsDocument>(e => e.Id == documents[0].Id || e.Id == documents[1].Id);
Assert.AreEqual(2, count);
}
}
}
-129
View File
@@ -1,129 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class DeleteTestsPartitionedDocument : PartitionedDocument
{
public DeleteTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 1;
}
public string SomeContent { get; set; }
}
public class DeletePartitionedTests : BaseMongoDbRepositoryTests<DeleteTestsPartitionedDocument>
{
[Test]
public void PartitionedDeleteOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.DeleteOne(document);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey));
}
[Test]
public void PartitionedDeleteOneLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.DeleteOne<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey));
}
[Test]
public async Task PartitionedDeleteOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.DeleteOneAsync(document);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey));
}
[Test]
public async Task PartitionedDeleteOneAsyncLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.DeleteOneAsync<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey));
}
[Test]
public async Task PartitionedDeleteManyAsyncLinq()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "DeleteManyAsyncLinqContent");
SUT.AddMany(documents);
// Act
var result = await SUT.DeleteManyAsync<DeleteTestsPartitionedDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent", PartitionKey);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<DeleteTestsPartitionedDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent", PartitionKey));
}
[Test]
public async Task PartitionedDeleteManyAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "DeleteManyAsyncLinqContent");
SUT.AddMany(documents);
// Act
var result = await SUT.DeleteManyAsync(documents);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<DeleteTestsPartitionedDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent", PartitionKey));
}
[Test]
public void PartitionedDeleteManyLinq()
{
// Arrange
var content = "DeleteManyLinqContent";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany(documents);
// Act
var result = SUT.DeleteMany<DeleteTestsPartitionedDocument>(e => e.SomeContent == content, PartitionKey);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<DeleteTestsPartitionedDocument>(e => e.SomeContent == content, PartitionKey));
}
[Test]
public void PartitionedDeleteMany()
{
// Arrange
var content = "DeleteManyContent";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany(documents);
// Act
var result = SUT.DeleteMany(documents);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<DeleteTestsPartitionedDocument>(e => e.SomeContent == content, PartitionKey));
}
}
}
-129
View File
@@ -1,129 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class DeleteTestsDocument : Document
{
public DeleteTestsDocument()
{
Version = 2;
}
public string SomeContent { get; set; }
}
public class DeleteTests : BaseMongoDbRepositoryTests<DeleteTestsDocument>
{
[Test]
public void DeleteOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.DeleteOne(document);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<DeleteTestsDocument>(e => e.Id == document.Id));
}
[Test]
public void DeleteOneLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.DeleteOne<DeleteTestsDocument>(e => e.Id == document.Id);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<DeleteTestsDocument>(e => e.Id == document.Id));
}
[Test]
public async Task DeleteOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.DeleteOneAsync(document);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<DeleteTestsDocument>(e => e.Id == document.Id));
}
[Test]
public async Task DeleteOneAsyncLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.DeleteOneAsync<DeleteTestsDocument>(e => e.Id == document.Id);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<DeleteTestsDocument>(e => e.Id == document.Id));
}
[Test]
public async Task DeleteManyAsyncLinq()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "DeleteManyAsyncLinqContent");
SUT.AddMany(documents);
// Act
var result = await SUT.DeleteManyAsync<DeleteTestsDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent");
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<DeleteTestsDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent"));
}
[Test]
public async Task DeleteManyAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "DeleteManyAsyncLinqContent");
SUT.AddMany(documents);
// Act
var result = await SUT.DeleteManyAsync(documents);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<DeleteTestsDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent"));
}
[Test]
public void DeleteManyLinq()
{
// Arrange
var content = "DeleteManyLinqContent";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany(documents);
// Act
var result = SUT.DeleteMany<DeleteTestsDocument>(e => e.SomeContent == content);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<DeleteTestsDocument>(e => e.SomeContent == content));
}
[Test]
public void DeleteMany()
{
// Arrange
var content = "DeleteManyContent";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany(documents);
// Act
var result = SUT.DeleteMany(documents);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<DeleteTestsDocument>(e => e.SomeContent == content));
}
}
}
@@ -5,7 +5,7 @@ using System.Configuration;
namespace IntegrationTests.Infrastructure
{
public class BaseMongoDbRepositoryTests<T> where T : Document, new()
public class BaseMongoDbRepositoryTests<T> where T : class, new()
{
public T CreateTestDocument()
{
@@ -0,0 +1,15 @@
using System;
namespace IntegrationTests.Infrastructure
{
/// <summary>
/// A class holding global variables.
/// </summary>
public static class GlobalVariables
{
/// <summary>
/// A random number generator.
/// </summary>
public static Random Random = new Random();
}
}
@@ -0,0 +1,821 @@
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<T>
where T: TestDoc, new()
{
public T CreateTestDocument()
{
return new T();
}
public abstract string GetClassName();
public List<T> CreateTestDocuments(int numberOfDocumentsToCreate)
{
var docs = new List<T>();
for (var i = 0; i < numberOfDocumentsToCreate; i++)
{
docs.Add(new T());
}
return docs;
}
/// <summary>
/// The partition key for the collection, if any
/// </summary>
protected string PartitionKey { get; set; }
/// <summary>
/// the name of the test class
/// </summary>
protected string TestClassName { get; set; }
/// <summary>
/// The name of the document used for tests
/// </summary>
protected string DocumentTypeName { get; set; }
/// <summary>
/// SUT: System Under Test
/// </summary>
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<T>(PartitionKey);
}
else
{
SUT.DropTestCollection<T>();
}
}
#region Add
[Test]
public void AddOne()
{
// Arrange
var document = new T();
// Act
SUT.AddOne<T>(document);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T>(e => e.Id.Equals(document.Id))
: SUT.Count<T>(e => e.Id.Equals(document.Id), PartitionKey);
Assert.AreEqual(1, count, GetTestName());
}
[Test]
public async Task AddOneAsync()
{
// Arrange
var document = new T();
// Act
await SUT.AddOneAsync<T>(document);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T>(e => e.Id.Equals(document.Id))
: SUT.Count<T>(e => e.Id.Equals(document.Id), PartitionKey);
Assert.AreEqual(1, count, GetTestName());
}
[Test]
public void AddMany()
{
// Arrange
var documents = new List<T> { new T(), new T() };
// Act
SUT.AddMany<T>(documents);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id))
: SUT.Count<T>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id), PartitionKey);
Assert.AreEqual(2, count, GetTestName());
}
[Test]
public async Task AddManyAsync()
{
// Arrange
var documents = new List<T> { new T(), new T() };
// Act
await SUT.AddManyAsync<T>(documents);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id))
: SUT.Count<T>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id), PartitionKey);
Assert.AreEqual(2, count, GetTestName());
}
#endregion Add
#region Read
[Test]
public async Task GetByIdAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.GetByIdAsync<T>(document.Id, PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
}
[Test]
public void GetById()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.GetById<T>(document.Id, PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
}
[Test]
public async Task GetOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.GetOneAsync<T>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
}
[Test]
public void GetOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.GetOne<T>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
}
[Test]
public void GetCursor()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var cursor = SUT.GetCursor<T>(x => x.Id.Equals(document.Id), PartitionKey);
var count = cursor.Count();
// Assert
Assert.AreEqual(1, count, GetTestName());
}
[Test]
public async Task AnyAsyncReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.AnyAsync<T>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.AreEqual(true, result, GetTestName());
}
[Test]
public async Task AnyAsyncReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.AnyAsync<T>(x => x.Id.Equals(Guid.NewGuid()), PartitionKey);
// Assert
Assert.AreEqual(false, result, GetTestName());
}
[Test]
public void AnyReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.Any<T>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.AreEqual(true, result, GetTestName());
}
[Test]
public void AnyReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.Any<T>(x => x.Id.Equals(Guid.NewGuid()), PartitionKey);
// Assert
Assert.AreEqual(false, result, GetTestName());
}
[Test]
public async Task GetAllAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
var content = GetContent();
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany<T>(documents);
// Act
var result = await SUT.GetAllAsync<T>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.AreEqual(5, result.Count, GetTestName());
}
[Test]
public void GetAll()
{
// Arrange
var documents = CreateTestDocuments(5);
var content = GetContent();
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany<T>(documents);
// Act
var result = SUT.GetAll<T>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.AreEqual(5, result.Count, GetTestName());
}
[Test]
public async Task CountAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
var content = GetContent();
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany<T>(documents);
// Act
var result = await SUT.CountAsync<T>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.AreEqual(5, result, GetTestName());
}
[Test]
public void Count()
{
// Arrange
var documents = CreateTestDocuments(5);
var content = GetContent();
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany<T>(documents);
// Act
var result = SUT.Count<T>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.AreEqual(5, result, GetTestName());
}
#endregion Read
#region Update
[Test]
public void UpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = SUT.UpdateOne<T>(document);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public async Task UpdateOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = await SUT.UpdateOneAsync<T>(document);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public void UpdateOneField()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, string>(document, x => x.SomeContent, content);
// Assert
Assert.IsTrue(result, GetTestName());
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public async Task UpdateOneFieldAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, string>(document, x => x.SomeContent, content);
// Assert
Assert.IsTrue(result, GetTestName());
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public void UpdateOneFieldWithFilter()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.IsTrue(result, GetTestName());
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public async Task UpdateOneFieldWithFilterAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.IsTrue(result, GetTestName());
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public async Task UpdateOneAsyncWithUpdateDefinition()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = await SUT.UpdateOneAsync<T>(document, updateDef);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument);
Assert.AreEqual(childrenToAdd[0].Type, updatedDocument.Children[0].Type, GetTestName());
Assert.AreEqual(childrenToAdd[0].Value, updatedDocument.Children[0].Value, GetTestName());
Assert.AreEqual(childrenToAdd[1].Type, updatedDocument.Children[1].Type, GetTestName());
Assert.AreEqual(childrenToAdd[1].Value, updatedDocument.Children[1].Value, GetTestName());
}
[Test]
public void UpdateOneWithUpdateDefinition()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = SUT.UpdateOne<T>(document, updateDef);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument);
Assert.AreEqual(childrenToAdd[0].Type, updatedDocument.Children[0].Type, GetTestName());
Assert.AreEqual(childrenToAdd[0].Value, updatedDocument.Children[0].Value, GetTestName());
Assert.AreEqual(childrenToAdd[1].Type, updatedDocument.Children[1].Type, GetTestName());
Assert.AreEqual(childrenToAdd[1].Value, updatedDocument.Children[1].Value, GetTestName());
}
#endregion Update
#region Delete
[Test]
public void DeleteOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.DeleteOne<T>(document);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<T>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Test]
public void DeleteOneLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = SUT.DeleteOne<T>(e => e.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<T>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Test]
public async Task DeleteOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.DeleteOneAsync<T>(document);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<T>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Test]
public async Task DeleteOneAsyncLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
// Act
var result = await SUT.DeleteOneAsync<T>(e => e.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<T>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Test]
public async Task DeleteManyAsyncLinq()
{
// Arrange
var criteria = $"{GetTestName()}.{DocumentTypeName}";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = criteria);
SUT.AddMany<T>(documents);
// Act
var result = await SUT.DeleteManyAsync<T>(e => e.SomeContent == criteria, PartitionKey);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<T>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
}
[Test]
public async Task DeleteManyAsync()
{
// Arrange
var criteria = $"{GetTestName()}.{DocumentTypeName}";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = criteria);
SUT.AddMany<T>(documents);
// Act
var result = await SUT.DeleteManyAsync<T>(documents);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<T>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
}
[Test]
public void DeleteManyLinq()
{
// Arrange
var criteria = $"{GetTestName()}.{DocumentTypeName}";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = criteria);
SUT.AddMany<T>(documents);
// Act
var result = SUT.DeleteMany<T>(e => e.SomeContent == criteria, PartitionKey);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<T>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
}
[Test]
public void DeleteMany()
{
// Arrange
var criteria = $"{GetTestName()}.{DocumentTypeName}";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = criteria);
SUT.AddMany<T>(documents);
// Act
var result = SUT.DeleteMany<T>(documents);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<T>(e => e.SomeContent == criteria, PartitionKey), 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;
SUT.AddOne<T>(document);
// Act
var result = await SUT.ProjectOneAsync<T, MyTestProjection>(
x => x.Id.Equals(document.Id),
x => new MyTestProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
Assert.AreEqual(someContent, result.SomeContent, GetTestName());
Assert.AreEqual(someDate.Minute, result.SomeDate.Minute, GetTestName());
Assert.AreEqual(someDate.Second, result.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<T>(document);
// Act
var result = SUT.ProjectOne<T, MyTestProjection>(
x => x.Id.Equals(document.Id),
x => new MyTestProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
Assert.AreEqual(someContent, result.SomeContent, GetTestName());
Assert.AreEqual(someDate.Minute, result.SomeDate.Minute, GetTestName());
Assert.AreEqual(someDate.Second, result.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;
});
SUT.AddMany<T>(documents);
// Act
var result = await SUT.ProjectManyAsync<T, MyTestProjection>(
x => x.SomeContent == someContent,
x => new MyTestProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.AreEqual(5, result.Count, GetTestName());
Assert.AreEqual(someContent, result.First().SomeContent, GetTestName());
Assert.AreEqual(someDate.Minute, result.First().SomeDate.Minute, GetTestName());
Assert.AreEqual(someDate.Second, result.First().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<T>(documents);
// Act
var result = SUT.ProjectMany<T, MyTestProjection>(
x => x.SomeContent == someContent,
x => new MyTestProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.AreEqual(5, result.Count, GetTestName());
Assert.AreEqual(someContent, result.First().SomeContent, GetTestName());
Assert.AreEqual(someDate.Minute, result.First().SomeDate.Minute, GetTestName());
Assert.AreEqual(someDate.Second, result.First().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<T, int, ProjectedGroup>(
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.AreEqual(3, key1Group.Content.Count);
var key2Group = result.First(e => e.Key == 2);
Assert.NotNull(key2Group);
Assert.AreEqual(2, key2Group.Content.Count);
}
[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<Child> {
new Child(guid1, guid2)
};
}
SUT.AddMany(documents);
// Act
var result = SUT.GroupBy<T, int, ProjectedGroup>(
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.AreEqual(3, key1Group.Content.Count);
var key2Group = result.First(e => e.Key == 5);
Assert.NotNull(key2Group);
Assert.AreEqual(1, key2Group.Content.Count);
}
#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
}
}
@@ -0,0 +1,735 @@
using MongoDB.Bson.Serialization.Attributes;
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<T, TKey>
where T: TestDoc<TKey>, new()
where TKey : IEquatable<TKey>
{
public T CreateTestDocument()
{
return new T();
}
public abstract string GetClassName();
public List<T> CreateTestDocuments(int numberOfDocumentsToCreate)
{
var docs = new List<T>();
for (var i = 0; i < numberOfDocumentsToCreate; i++)
{
docs.Add(new T());
}
return docs;
}
/// <summary>
/// The partition key for the collection, if any
/// </summary>
protected string PartitionKey { get; set; }
/// <summary>
/// the name of the test class
/// </summary>
protected string TestClassName { get; set; }
/// <summary>
/// The name of the document used for tests
/// </summary>
protected string DocumentTypeName { get; set; }
/// <summary>
/// SUT: System Under Test
/// </summary>
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<T>(PartitionKey);
}
else
{
SUT.DropTestCollection<T>();
}
}
#region Add
[Test]
public void AddOne()
{
// Arrange
var document = new T();
// Act
SUT.AddOne<T, TKey>(document);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T, TKey>(e => e.Id.Equals(document.Id))
: SUT.Count<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey);
Assert.AreEqual(1, count, GetTestName());
}
[Test]
public async Task AddOneAsync()
{
// Arrange
var document = new T();
// Act
await SUT.AddOneAsync<T, TKey>(document);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T, TKey>(e => e.Id.Equals(document.Id))
: SUT.Count<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey);
Assert.AreEqual(1, count, GetTestName());
}
[Test]
public void AddMany()
{
// Arrange
var documents = new List<T> { new T(), new T() };
// Act
SUT.AddMany<T, TKey>(documents);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T, TKey>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id))
: SUT.Count<T, TKey>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id), PartitionKey);
Assert.AreEqual(2, count, GetTestName());
}
[Test]
public async Task AddManyAsync()
{
// Arrange
var documents = new List<T> { new T(), new T() };
// Act
await SUT.AddManyAsync<T, TKey>(documents);
// Assert
long count = string.IsNullOrEmpty(PartitionKey) ? SUT.Count<T, TKey>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id))
: SUT.Count<T, TKey>(e => e.Id.Equals(documents[0].Id)
|| e.Id.Equals(documents[1].Id), PartitionKey);
Assert.AreEqual(2, count, GetTestName());
}
#endregion Add
#region Read
[Test]
public async Task GetByIdAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.GetByIdAsync<T, TKey>(document.Id, PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
}
[Test]
public void GetById()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.GetById<T, TKey>(document.Id, PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
}
[Test]
public async Task GetOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.GetOneAsync<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
}
[Test]
public void GetOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.GetOne<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
}
[Test]
public void GetCursor()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var cursor = SUT.GetCursor<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
var count = cursor.Count();
// Assert
Assert.AreEqual(1, count, GetTestName());
}
[Test]
public async Task AnyAsyncReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.AnyAsync<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.AreEqual(true, result, GetTestName());
}
[Test]
public async Task AnyAsyncReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.AnyAsync<T, TKey>(x => x.Id.Equals(document.Init<TKey>()), PartitionKey);
// Assert
Assert.AreEqual(false, result, GetTestName());
}
[Test]
public void AnyReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.Any<T, TKey>(x => x.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.AreEqual(true, result, GetTestName());
}
[Test]
public void AnyReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.Any<T, TKey>(x => x.Id.Equals(document.Init<TKey>()), PartitionKey);
// Assert
Assert.AreEqual(false, result, GetTestName());
}
[Test]
public async Task GetAllAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
var content = GetContent();
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany<T, TKey>(documents);
// Act
var result = await SUT.GetAllAsync<T, TKey>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.AreEqual(5, result.Count, GetTestName());
}
[Test]
public void GetAll()
{
// Arrange
var documents = CreateTestDocuments(5);
var content = GetContent();
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany<T, TKey>(documents);
// Act
var result = SUT.GetAll<T, TKey>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.AreEqual(5, result.Count, GetTestName());
}
[Test]
public async Task CountAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
var content = GetContent();
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany<T, TKey>(documents);
// Act
var result = await SUT.CountAsync<T, TKey>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.AreEqual(5, result, GetTestName());
}
[Test]
public void Count()
{
// Arrange
var documents = CreateTestDocuments(5);
var content = GetContent();
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany<T, TKey>(documents);
// Act
var result = SUT.Count<T, TKey>(x => x.SomeContent == content, PartitionKey);
// Assert
Assert.AreEqual(5, result, GetTestName());
}
#endregion Read
#region Update
[Test]
public void UpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = SUT.UpdateOne<T, TKey>(document);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public async Task UpdateOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = await SUT.UpdateOneAsync<T, TKey>(document);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public void UpdateOneField()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, TKey, string>(document, x => x.SomeContent, content);
// Assert
Assert.IsTrue(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public async Task UpdateOneFieldAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, TKey, string>(document, x => x.SomeContent, content);
// Assert
Assert.IsTrue(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public void UpdateOneFieldWithFilter()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, TKey, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.IsTrue(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public async Task UpdateOneFieldWithFilterAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, TKey, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.IsTrue(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument, GetTestName());
Assert.AreEqual(content, updatedDocument.SomeContent, GetTestName());
}
[Test]
public async Task UpdateOneAsyncWithUpdateDefinition()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = await SUT.UpdateOneAsync<T, TKey>(document, updateDef);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument);
Assert.AreEqual(childrenToAdd[0].Type, updatedDocument.Children[0].Type, GetTestName());
Assert.AreEqual(childrenToAdd[0].Value, updatedDocument.Children[0].Value, GetTestName());
Assert.AreEqual(childrenToAdd[1].Type, updatedDocument.Children[1].Type, GetTestName());
Assert.AreEqual(childrenToAdd[1].Value, updatedDocument.Children[1].Value, GetTestName());
}
[Test]
public void UpdateOneWithUpdateDefinition()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = SUT.UpdateOne<T, TKey>(document, updateDef);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument);
Assert.AreEqual(childrenToAdd[0].Type, updatedDocument.Children[0].Type, GetTestName());
Assert.AreEqual(childrenToAdd[0].Value, updatedDocument.Children[0].Value, GetTestName());
Assert.AreEqual(childrenToAdd[1].Type, updatedDocument.Children[1].Type, GetTestName());
Assert.AreEqual(childrenToAdd[1].Value, updatedDocument.Children[1].Value, GetTestName());
}
#endregion Update
#region Delete
[Test]
public void DeleteOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.DeleteOne<T, TKey>(document);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Test]
public void DeleteOneLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = SUT.DeleteOne<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Test]
public async Task DeleteOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.DeleteOneAsync<T, TKey>(document);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Test]
public async Task DeleteOneAsyncLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.DeleteOneAsync<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey);
// Assert
Assert.AreEqual(1, result);
Assert.IsFalse(SUT.Any<T, TKey>(e => e.Id.Equals(document.Id), PartitionKey), GetTestName());
}
[Test]
public async Task DeleteManyAsyncLinq()
{
// Arrange
var criteria = $"{GetTestName()}.{DocumentTypeName}";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = criteria);
SUT.AddMany<T, TKey>(documents);
// Act
var result = await SUT.DeleteManyAsync<T, TKey>(e => e.SomeContent == criteria, PartitionKey);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<T, TKey>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
}
[Test]
public async Task DeleteManyAsync()
{
// Arrange
var criteria = $"{GetTestName()}.{DocumentTypeName}";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = criteria);
SUT.AddMany<T, TKey>(documents);
// Act
var result = await SUT.DeleteManyAsync<T, TKey>(documents);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<T, TKey>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
}
[Test]
public void DeleteManyLinq()
{
// Arrange
var criteria = $"{GetTestName()}.{DocumentTypeName}";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = criteria);
SUT.AddMany<T, TKey>(documents);
// Act
var result = SUT.DeleteMany<T, TKey>(e => e.SomeContent == criteria, PartitionKey);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<T, TKey>(e => e.SomeContent == criteria, PartitionKey), GetTestName());
}
[Test]
public void DeleteMany()
{
// Arrange
var criteria = $"{GetTestName()}.{DocumentTypeName}";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = criteria);
SUT.AddMany<T, TKey>(documents);
// Act
var result = SUT.DeleteMany<T, TKey>(documents);
// Assert
Assert.AreEqual(5, result);
Assert.IsFalse(SUT.Any<T, TKey>(e => e.SomeContent == criteria, PartitionKey), 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;
SUT.AddOne<T, TKey>(document);
// Act
var result = await SUT.ProjectOneAsync<T, MyTestProjection, TKey>(
x => x.Id.Equals(document.Id),
x => new MyTestProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
Assert.AreEqual(someContent, result.SomeContent, GetTestName());
Assert.AreEqual(someDate.Minute, result.SomeDate.Minute, GetTestName());
Assert.AreEqual(someDate.Second, result.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<T, TKey>(document);
// Act
var result = SUT.ProjectOne<T, MyTestProjection, TKey>(
x => x.Id.Equals(document.Id),
x => new MyTestProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.IsNotNull(result, GetTestName());
Assert.AreEqual(someContent, result.SomeContent, GetTestName());
Assert.AreEqual(someDate.Minute, result.SomeDate.Minute, GetTestName());
Assert.AreEqual(someDate.Second, result.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;
});
SUT.AddMany<T, TKey>(documents);
// Act
var result = await SUT.ProjectManyAsync<T, MyTestProjection, TKey>(
x => x.SomeContent == someContent,
x => new MyTestProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.AreEqual(5, result.Count, GetTestName());
Assert.AreEqual(someContent, result.First().SomeContent, GetTestName());
Assert.AreEqual(someDate.Minute, result.First().SomeDate.Minute, GetTestName());
Assert.AreEqual(someDate.Second, result.First().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<T, TKey>(documents);
// Act
var result = SUT.ProjectMany<T, MyTestProjection, TKey>(
x => x.SomeContent == someContent,
x => new MyTestProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.AreEqual(5, result.Count, GetTestName());
Assert.AreEqual(someContent, result.First().SomeContent, GetTestName());
Assert.AreEqual(someDate.Minute, result.First().SomeDate.Minute, GetTestName());
Assert.AreEqual(someDate.Second, result.First().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
}
}
@@ -0,0 +1,61 @@
using System;
namespace IntegrationTests.Infrastructure
{
// Thanks BlueRaja - Danny Pflughoeft https://stackoverflow.com/a/13095144/5103354
/// <summary>
/// Extensions for the random number generator <see cref="Random"/>
/// </summary>
public static class RandomExtensions
{
/// <summary>
/// Returns a random long from min (inclusive) to max (exclusive)
/// </summary>
/// <param name="random">The given random instance</param>
/// <param name="min">The inclusive minimum bound</param>
/// <param name="max">The exclusive maximum bound. Must be greater than min</param>
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;
}
/// <summary>
/// Returns a random long from 0 (inclusive) to max (exclusive)
/// </summary>
/// <param name="random">The given random instance</param>
/// <param name="max">The exclusive maximum bound. Must be greater than 0</param>
public static long NextLong(this Random random, long max)
{
return random.NextLong(0, max);
}
/// <summary>
/// Returns a random long over all possible values of long (except long.MaxValue, similar to
/// random.Next())
/// </summary>
/// <param name="random">The given random instance</param>
public static long NextLong(this Random random)
{
return random.NextLong(long.MinValue, long.MaxValue);
}
}
}
@@ -0,0 +1,94 @@
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<string> 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<Child>();
}
public string SomeContent { get; set; }
public int GroupingKey { get; set; }
public Nested Nested { get; set; }
public List<Child> Children { get; set; }
}
public class TestDoc<TKey> : IDocument<TKey>
where TKey : IEquatable<TKey>
{
[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<Child>();
}
public string SomeContent { get; set; }
public Nested Nested { get; set; }
public List<Child> Children { get; set; }
public TId Init<TId>()
{
return IdGenerator.GetId<TId>();
}
private void InitializeFields()
{
Id = Init<TKey>();
}
}
}
@@ -1,4 +1,9 @@
using MongoDbGenericRepository;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.Models;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace IntegrationTests.Infrastructure
{
@@ -11,12 +16,27 @@ namespace IntegrationTests.Infrastructure
public void DropTestCollection<TDocument>()
{
_mongoDbContext.DropCollection<TDocument>();
MongoDbContext.DropCollection<TDocument>();
}
public void DropTestCollection<TDocument>(string partitionKey)
{
_mongoDbContext.DropCollection<TDocument>(partitionKey);
MongoDbContext.DropCollection<TDocument>(partitionKey);
}
/// <summary>
/// Gets the max of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <returns></returns>
public async Task<TDocument> GetByMaxAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByDescending)
where TDocument : IDocument<TKey>
where TKey : System.IEquatable<TKey>
{
return await GetCollection<TDocument, TKey>().Find(Builders<TDocument>.Filter.Where(filter))
.SortByDescending(orderByDescending)
.FirstOrDefaultAsync();
}
}
}
+32 -32
View File
@@ -30,46 +30,52 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="MongoDB.Bson, Version=2.4.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Bson.2.4.4\lib\net45\MongoDB.Bson.dll</HintPath>
<Reference Include="DnsClient, Version=1.0.7.0, Culture=neutral, PublicKeyToken=4574bb5573c51424, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDbGenericRepository.1.3.7\lib\net45\DnsClient.dll</HintPath>
</Reference>
<Reference Include="MongoDB.Driver, Version=2.4.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Driver.2.4.4\lib\net45\MongoDB.Driver.dll</HintPath>
<Reference Include="MongoDB.Bson, Version=2.7.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDbGenericRepository.1.3.7\lib\net45\MongoDB.Bson.dll</HintPath>
</Reference>
<Reference Include="MongoDB.Driver.Core, Version=2.4.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Driver.Core.2.4.4\lib\net45\MongoDB.Driver.Core.dll</HintPath>
<Reference Include="MongoDB.Driver, Version=2.7.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDbGenericRepository.1.3.7\lib\net45\MongoDB.Driver.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=3.7.1.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.7.1\lib\net45\nunit.framework.dll</HintPath>
<Reference Include="MongoDB.Driver.Core, Version=2.7.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDbGenericRepository.1.3.7\lib\net45\MongoDB.Driver.Core.dll</HintPath>
</Reference>
<Reference Include="MongoDbGenericRepository, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDbGenericRepository.1.3.7\lib\net45\MongoDbGenericRepository.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=3.9.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.9.0\lib\net45\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDbGenericRepository.1.3.7\lib\net45\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDbGenericRepository.1.3.7\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="DeletePartitionedTests.cs" />
<Compile Include="DeleteTests.cs" />
<Compile Include="CRUDObjectIdTests.cs" />
<Compile Include="CRUDPartitionedTests.cs" />
<Compile Include="CRUDTKeyPartitionedCollectionNameAttributeTests.cs" />
<Compile Include="CRUDTests.cs" />
<Compile Include="CRUDPartitionedCollectionNameAttributeTests.cs" />
<Compile Include="CRUDTKeyPartitionedTests.cs" />
<Compile Include="CRUDTKeyTests.cs" />
<Compile Include="Infrastructure\BaseMongoDbRepositoryTests.cs" />
<Compile Include="CreatePartitionedTests.cs" />
<Compile Include="Infrastructure\GlobalVariables.cs" />
<Compile Include="Infrastructure\ITestRepository.cs" />
<Compile Include="Infrastructure\MongoDbDocumentTestBase.cs" />
<Compile Include="Infrastructure\MongoDbTKeyDocumentTestBase.cs" />
<Compile Include="Infrastructure\RandomExtensions.cs" />
<Compile Include="Infrastructure\TestClasses.cs" />
<Compile Include="Infrastructure\TestRepository.cs" />
<Compile Include="CreateTests.cs" />
<Compile Include="ProjectPartitionedTests.cs" />
<Compile Include="ProjectTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ReadPartitionedTests.cs" />
<Compile Include="ReadTests.cs" />
<Compile Include="UpdatePartitionedTests.cs" />
<Compile Include="UpdateTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config">
@@ -77,12 +83,6 @@
</None>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MongoDbGenericRepository\MongoDbGenericRepository.csproj">
<Project>{d154e7d0-9a3c-43ab-8e90-ed92bc4343f0}</Project>
<Name>MongoDbGenericRepository</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
-140
View File
@@ -1,140 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class ProjectTestsPartitionedDocument : PartitionedDocument
{
public ProjectTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 2;
Nested = new Nested
{
SomeDate = DateTime.UtcNow
};
}
public string SomeContent { get; set; }
public Nested Nested { get; set; }
}
public class ProjectPartitionedTests : BaseMongoDbRepositoryTests<ProjectTestsPartitionedDocument>
{
[Test]
public async Task PartitionedProjectOneAsync()
{
// Arrange
const string someContent = "ProjectOneAsyncContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocument();
document.SomeContent = someContent;
document.Nested.SomeDate = someDate;
SUT.AddOne(document);
// Act
var result = await SUT.ProjectOneAsync<ProjectTestsPartitionedDocument, MyProjection>(
x => x.Id == document.Id,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(someContent, result.SomeContent);
Assert.AreEqual(someDate.Minute, result.SomeDate.Minute);
Assert.AreEqual(someDate.Second, result.SomeDate.Second);
}
[Test]
public void PartitionedProjectOne()
{
// Arrange
const string someContent = "ProjectOneContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocument();
document.SomeContent = someContent;
document.Nested.SomeDate = someDate;
SUT.AddOne(document);
// Act
var result = SUT.ProjectOne<ProjectTestsPartitionedDocument, MyProjection>(
x => x.Id == document.Id,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(someContent, result.SomeContent);
Assert.AreEqual(someDate.Minute, result.SomeDate.Minute);
Assert.AreEqual(someDate.Second, result.SomeDate.Second);
}
[Test]
public async Task PartitionedProjectManyAsync()
{
// Arrange
const string someContent = "ProjectManyAsyncContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocuments(5);
document.ForEach(e =>
{
e.SomeContent = someContent;
e.Nested.SomeDate = someDate;
});
SUT.AddMany(document);
// Act
var result = await SUT.ProjectManyAsync<ProjectTestsPartitionedDocument, MyProjection>(
x => x.SomeContent == someContent,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.AreEqual(5, result.Count);
Assert.AreEqual(someContent, result.First().SomeContent);
Assert.AreEqual(someDate.Minute, result.First().SomeDate.Minute);
Assert.AreEqual(someDate.Second, result.First().SomeDate.Second);
}
[Test]
public void PartitionedProjectMany()
{
// Arrange
const string someContent = "ProjectManyContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocuments(5);
document.ForEach(e =>
{
e.SomeContent = someContent;
e.Nested.SomeDate = someDate;
});
SUT.AddMany(document);
// Act
var result = SUT.ProjectMany<ProjectTestsPartitionedDocument, MyProjection>(
x => x.SomeContent == someContent,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.AreEqual(5, result.Count);
Assert.AreEqual(someContent, result.First().SomeContent);
Assert.AreEqual(someDate.Minute, result.First().SomeDate.Minute);
Assert.AreEqual(someDate.Second, result.First().SomeDate.Second);
}
}
}
-149
View File
@@ -1,149 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class Nested
{
public DateTime SomeDate { get; set; }
}
public class MyProjection
{
public DateTime SomeDate { get; set; }
public string SomeContent { get; set; }
}
public class ProjectTestsDocument : Document
{
public ProjectTestsDocument()
{
Version = 2;
Nested = new Nested
{
SomeDate = DateTime.UtcNow
};
}
public string SomeContent { get; set; }
public Nested Nested { get; set; }
}
public class ProjectTests : BaseMongoDbRepositoryTests<ProjectTestsDocument>
{
[Test]
public async Task ProjectOneAsync()
{
// Arrange
const string someContent = "ProjectOneAsyncContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocument();
document.SomeContent = someContent;
document.Nested.SomeDate = someDate;
SUT.AddOne(document);
// Act
var result = await SUT.ProjectOneAsync<ProjectTestsDocument, MyProjection>(
x => x.Id == document.Id,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
});
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(someContent, result.SomeContent);
Assert.AreEqual(someDate.Minute, result.SomeDate.Minute);
Assert.AreEqual(someDate.Second, result.SomeDate.Second);
}
[Test]
public void ProjectOne()
{
// Arrange
const string someContent = "ProjectOneContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocument();
document.SomeContent = someContent;
document.Nested.SomeDate = someDate;
SUT.AddOne(document);
// Act
var result = SUT.ProjectOne<ProjectTestsDocument, MyProjection>(
x => x.Id == document.Id,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
});
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(someContent, result.SomeContent);
Assert.AreEqual(someDate.Minute, result.SomeDate.Minute);
Assert.AreEqual(someDate.Second, result.SomeDate.Second);
}
[Test]
public async Task ProjectManyAsync()
{
// Arrange
const string someContent = "ProjectManyAsyncContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocuments(5);
document.ForEach(e =>
{
e.SomeContent = someContent;
e.Nested.SomeDate = someDate;
});
SUT.AddMany(document);
// Act
var result = await SUT.ProjectManyAsync<ProjectTestsDocument, MyProjection>(
x => x.SomeContent == someContent,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
});
// Assert
Assert.AreEqual(5, result.Count);
Assert.AreEqual(someContent, result.First().SomeContent);
Assert.AreEqual(someDate.Minute, result.First().SomeDate.Minute);
Assert.AreEqual(someDate.Second, result.First().SomeDate.Second);
}
[Test]
public void ProjectMany()
{
// Arrange
const string someContent = "ProjectManyContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocuments(5);
document.ForEach(e =>
{
e.SomeContent = someContent;
e.Nested.SomeDate = someDate;
});
SUT.AddMany(document);
// Act
var result = SUT.ProjectMany<ProjectTestsDocument, MyProjection>(
x => x.SomeContent == someContent,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
});
// Assert
Assert.AreEqual(5, result.Count);
Assert.AreEqual(someContent, result.First().SomeContent);
Assert.AreEqual(someDate.Minute, result.First().SomeDate.Minute);
Assert.AreEqual(someDate.Second, result.First().SomeDate.Second);
}
}
}
-181
View File
@@ -1,181 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class ReadTestsPartitionedDocument : PartitionedDocument
{
public ReadTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 1;
}
public string SomeContent { get; set; }
}
public class ReadPartitionedTests : BaseMongoDbRepositoryTests<ReadTestsPartitionedDocument>
{
[Test]
public async Task PartitionedGetByIdAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.GetByIdAsync<ReadTestsPartitionedDocument>(document.Id, PartitionKey);
// Assert
Assert.IsNotNull(result);
}
[Test]
public void PartitionedGetById()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.GetById<ReadTestsPartitionedDocument>(document.Id, PartitionKey);
// Assert
Assert.IsNotNull(result);
}
[Test]
public async Task PartitionedGetOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.GetOneAsync<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
// Assert
Assert.IsNotNull(result);
}
[Test]
public void PartitionedGetOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.GetOne<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
// Assert
Assert.IsNotNull(result);
}
[Test]
public void PartitionedGetCursor()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var cursor = SUT.GetCursor<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
var count = cursor.Count();
// Assert
Assert.AreEqual(1, count);
}
[Test]
public async Task PartitionedAnyAsyncReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.AnyAsync<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
// Assert
Assert.AreEqual(true, result);
}
[Test]
public async Task PartitionedAnyAsyncReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.AnyAsync<ReadTestsPartitionedDocument>(x => x.Id == Guid.NewGuid(), PartitionKey);
// Assert
Assert.AreEqual(false, result);
}
[Test]
public void PartitionedAnyReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.Any<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
// Assert
Assert.AreEqual(true, result);
}
[Test]
public void PartitionedAnyReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.Any<ReadTestsPartitionedDocument>(x => x.Id == Guid.NewGuid(), PartitionKey);
// Assert
Assert.AreEqual(false, result);
}
[Test]
public async Task PartitionedGetAllAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "GetAllAsyncContent");
SUT.AddMany(documents);
// Act
var result = await SUT.GetAllAsync<ReadTestsPartitionedDocument>(x => x.SomeContent == "GetAllAsyncContent", PartitionKey);
// Assert
Assert.AreEqual(5, result.Count);
}
[Test]
public void PartitionedGetAll()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "GetAllContent");
SUT.AddMany(documents);
// Act
var result = SUT.GetAll<ReadTestsPartitionedDocument>(x => x.SomeContent == "GetAllContent", PartitionKey);
// Assert
Assert.AreEqual(5, result.Count);
}
[Test]
public async Task PartitionedCountAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "CountAsyncContent");
SUT.AddMany(documents);
// Act
var result = await SUT.CountAsync<ReadTestsPartitionedDocument>(x => x.SomeContent == "CountAsyncContent", PartitionKey);
// Assert
Assert.AreEqual(5, result);
}
[Test]
public void PartitionedCount()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "CountContent");
SUT.AddMany(documents);
// Act
var result = SUT.Count<ReadTestsPartitionedDocument>(x => x.SomeContent == "CountContent", PartitionKey);
// Assert
Assert.AreEqual(5, result);
}
}
}
-182
View File
@@ -1,182 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class ReadTestsDocument : Document
{
public ReadTestsDocument()
{
Version = 2;
}
public string SomeContent { get; set; }
}
[TestFixture]
public class ReadTests : BaseMongoDbRepositoryTests<ReadTestsDocument>
{
[Test]
public async Task GetByIdAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.GetByIdAsync<ReadTestsDocument>(document.Id);
// Assert
Assert.IsNotNull(result);
}
[Test]
public void GetById()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.GetById<ReadTestsDocument>(document.Id);
// Assert
Assert.IsNotNull(result);
}
[Test]
public async Task GetOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.GetOneAsync<ReadTestsDocument>(x => x.Id == document.Id);
// Assert
Assert.IsNotNull(result);
}
[Test]
public void GetOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.GetOne<ReadTestsDocument>(x => x.Id == document.Id);
// Assert
Assert.IsNotNull(result);
}
[Test]
public void GetCursor()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var cursor = SUT.GetCursor<ReadTestsDocument>(x => x.Id == document.Id);
var count = cursor.Count();
// Assert
Assert.AreEqual(1, count);
}
[Test]
public async Task AnyAsyncReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.AnyAsync<ReadTestsDocument>(x => x.Id == document.Id);
// Assert
Assert.AreEqual(true, result);
}
[Test]
public async Task AnyAsyncReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.AnyAsync<ReadTestsDocument>(x => x.Id == Guid.NewGuid());
// Assert
Assert.AreEqual(false, result);
}
[Test]
public void AnyReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.Any<ReadTestsDocument>(x => x.Id == document.Id);
// Assert
Assert.AreEqual(true, result);
}
[Test]
public void AnyReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.Any<ReadTestsDocument>(x => x.Id == Guid.NewGuid());
// Assert
Assert.AreEqual(false, result);
}
[Test]
public async Task GetAllAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "GetAllAsyncContent");
SUT.AddMany(documents);
// Act
var result = await SUT.GetAllAsync<ReadTestsDocument>(x => x.SomeContent == "GetAllAsyncContent");
// Assert
Assert.AreEqual(5, result.Count);
}
[Test]
public void GetAll()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "GetAllContent");
SUT.AddMany(documents);
// Act
var result = SUT.GetAll<ReadTestsDocument>(x => x.SomeContent == "GetAllContent");
// Assert
Assert.AreEqual(5, result.Count);
}
[Test]
public async Task CountAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "CountAsyncContent");
SUT.AddMany(documents);
// Act
var result = await SUT.CountAsync<ReadTestsDocument>(x => x.SomeContent == "CountAsyncContent");
// Assert
Assert.AreEqual(5, result);
}
[Test]
public void Count()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "CountContent");
SUT.AddMany(documents);
// Act
var result = SUT.Count<ReadTestsDocument>(x => x.SomeContent == "CountContent");
// Assert
Assert.AreEqual(5, result);
}
}
}
@@ -1,51 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class UpdateTestsPartitionedDocument : PartitionedDocument
{
public UpdateTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 2;
}
public string SomeContent { get; set; }
}
public class UpdatePartitionedTests : BaseMongoDbRepositoryTests<UpdateTestsPartitionedDocument>
{
[Test]
public void PartitionedUpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
document.SomeContent = "UpdateOneContent";
// Act
var result = SUT.UpdateOne(document);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<UpdateTestsPartitionedDocument>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument);
Assert.AreEqual("UpdateOneContent", updatedDocument.SomeContent);
}
[Test]
public async Task PartitionedUpdateOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
document.SomeContent = "UpdateOneAsyncContent";
// Act
var result = await SUT.UpdateOneAsync(document);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<UpdateTestsPartitionedDocument>(document.Id, PartitionKey);
Assert.IsNotNull(updatedDocument);
Assert.AreEqual("UpdateOneAsyncContent", updatedDocument.SomeContent);
}
}
}
-51
View File
@@ -1,51 +0,0 @@
using IntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using NUnit.Framework;
using System.Threading.Tasks;
namespace IntegrationTests
{
public class UpdateTestsDocument : Document
{
public UpdateTestsDocument()
{
Version = 2;
}
public string SomeContent { get; set; }
}
public class UpdateTests : BaseMongoDbRepositoryTests<UpdateTestsDocument>
{
[Test]
public void UpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
document.SomeContent = "UpdateOneContent";
// Act
var result = SUT.UpdateOne(document);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<UpdateTestsDocument>(document.Id);
Assert.IsNotNull(updatedDocument);
Assert.AreEqual("UpdateOneContent", updatedDocument.SomeContent);
}
[Test]
public async Task UpdateOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
document.SomeContent = "UpdateOneAsyncContent";
// Act
var result = await SUT.UpdateOneAsync(document);
// Assert
Assert.IsTrue(result);
var updatedDocument = SUT.GetById<UpdateTestsDocument>(document.Id);
Assert.IsNotNull(updatedDocument);
Assert.AreEqual("UpdateOneAsyncContent", updatedDocument.SomeContent);
}
}
}
@@ -1,3 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
</ApplicationInsights>
@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="MongoDbTests" connectionString="mongodb://localhost:27017" />
</connectionStrings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
@@ -1,32 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
Binary file not shown.
File diff suppressed because it is too large Load Diff
@@ -1,40 +0,0 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>Microsoft.CodeDom.Providers.DotNetCompilerPlatform</name>
</assembly>
<members>
<member name="T:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider">
<summary>
Provides access to instances of the .NET Compiler Platform C# code generator and code compiler.
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider.#ctor">
<summary>
Default Constructor
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider.CreateCompiler">
<summary>
Gets an instance of the .NET Compiler Platform C# code compiler.
</summary>
<returns>An instance of the .NET Compiler Platform C# code compiler</returns>
</member>
<member name="T:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider">
<summary>
Provides access to instances of the .NET Compiler Platform VB code generator and code compiler.
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider.#ctor">
<summary>
Default Constructor
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider.CreateCompiler">
<summary>
Gets an instance of the .NET Compiler Platform VB code compiler.
</summary>
<returns>An instance of the .NET Compiler Platform VB code compiler</returns>
</member>
</members>
</doc>
@@ -1,19 +0,0 @@
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\ApplicationInsights.config
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\IntegrationTests.dll.config
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\IntegrationTests.dll
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\IntegrationTests.pdb
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\MongoDbGenericRepository.dll
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\nunit.framework.dll
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\MongoDB.Driver.dll
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\MongoDB.Bson.dll
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\MongoDB.Driver.Core.dll
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\MongoDbGenericRepository.pdb
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\MongoDbGenericRepository.dll.config
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\nunit.framework.xml
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\MongoDB.Driver.xml
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\MongoDB.Bson.xml
C:\dev\MongoDbRepoUpdate\IntegrationTests\obj\Debug\IntegrationTests.csprojResolveAssemblyReference.cache
C:\dev\MongoDbRepoUpdate\IntegrationTests\obj\Debug\IntegrationTests.dll
C:\dev\MongoDbRepoUpdate\IntegrationTests\obj\Debug\IntegrationTests.pdb
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\System.Runtime.InteropServices.RuntimeInformation.dll
C:\dev\MongoDbRepoUpdate\IntegrationTests\bin\Debug\MongoDB.Driver.Core.xml
+8 -5
View File
@@ -1,9 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MongoDB.Bson" version="2.4.4" targetFramework="net461" />
<package id="MongoDB.Driver" version="2.4.4" targetFramework="net461" />
<package id="MongoDB.Driver.Core" version="2.4.4" targetFramework="net461" />
<package id="NUnit" version="3.7.1" targetFramework="net461" />
<package id="DnsClient" version="1.0.7" targetFramework="net461" />
<package id="MongoDB.Bson" version="2.7.0" targetFramework="net461" />
<package id="MongoDB.Driver" version="2.7.0" targetFramework="net461" />
<package id="MongoDB.Driver.Core" version="2.7.0" targetFramework="net461" />
<package id="MongoDbGenericRepository" version="1.3.7" targetFramework="net461" />
<package id="NUnit" version="3.9.0" targetFramework="net461" />
<package id="NUnit.ConsoleRunner" version="3.7.0" targetFramework="net461" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net461" />
<package id="System.Buffers" version="4.3.0" targetFramework="net461" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.0.0" targetFramework="net461" />
</packages>
+21
View File
@@ -0,0 +1,21 @@
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.
+16 -7
View File
@@ -1,28 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26430.16
VisualStudioVersion = 15.0.26730.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDbGenericRepository", "MongoDbGenericRepository\MongoDbGenericRepository.csproj", "{D154E7D0-9A3C-43AB-8E90-ED92BC4343F0}"
EndProject
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
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D154E7D0-9A3C-43AB-8E90-ED92BC4343F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D154E7D0-9A3C-43AB-8E90-ED92BC4343F0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D154E7D0-9A3C-43AB-8E90-ED92BC4343F0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D154E7D0-9A3C-43AB-8E90-ED92BC4343F0}.Release|Any CPU.Build.0 = Release|Any CPU
{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
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {78214390-EFBD-403C-8AAA-5CD4CA5AE2ED}
EndGlobalSection
EndGlobal
@@ -0,0 +1,698 @@
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq.Expressions;
using MongoDbGenericRepository.Models;
using System.Linq;
namespace MongoDbGenericRepository
{
/// <summary>
/// The IBaseMongoRepository exposes the CRUD functionality of the BaseMongoRepository.
/// </summary>
public interface IBaseMongoRepository : IReadOnlyMongoRepository
{
#region Create
/// <summary>
/// Asynchronously adds a document to the collection.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="document">The document you want to add.</param>
Task AddOneAsync<TDocument>(TDocument document) where TDocument : IDocument;
/// <summary>
/// Adds a document to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="document">The document you want to add.</param>
void AddOne<TDocument>(TDocument document) where TDocument : IDocument;
/// <summary>
/// Asynchronously adds a list of documents to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="documents">The document you want to add.</param>
Task AddManyAsync<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument;
/// <summary>
/// Adds a list of documents to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="documents">The document you want to add.</param>
void AddMany<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument;
#endregion
#region Create TKey
/// <summary>
/// Asynchronously adds a document to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="document">The document you want to add.</param>
Task AddOneAsync<TDocument, TKey>(TDocument document)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Adds a document to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="document">The document you want to add.</param>
void AddOne<TDocument, TKey>(TDocument document)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Asynchronously adds a list of documents to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="documents">The documents you want to add.</param>
Task AddManyAsync<TDocument, TKey>(IEnumerable<TDocument> documents)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Adds a list of documents to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="documents">The documents you want to add.</param>
void AddMany<TDocument, TKey>(IEnumerable<TDocument> documents)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
#endregion
#region Update
/// <summary>
/// Asynchronously Updates a document.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="modifiedDocument">The document with the modifications you want to persist.</param>
Task<bool> UpdateOneAsync<TDocument>(TDocument modifiedDocument) where TDocument : IDocument;
/// <summary>
/// Updates a document.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="modifiedDocument">The document with the modifications you want to persist.</param>
bool UpdateOne<TDocument>(TDocument modifiedDocument) where TDocument : IDocument;
/// <summary>
/// Updates the property field with the given value update a property field in entities.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="filter">The document filter.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
/// <param name="partitionKey">The value of the partition key.</param>
bool UpdateOne<TDocument, TField>(FilterDefinition<TDocument> filter, Expression<Func<TDocument, TField>> field, TField value, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Updates the property field with the given value update a property field in entities.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="filter">The document filter.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
/// <param name="partitionKey">The value of the partition key.</param>
Task<bool> UpdateOneAsync<TDocument, TField>(FilterDefinition<TDocument> filter, Expression<Func<TDocument, TField>> field, TField value, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Updates the property field with the given value update a property field in entities.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="documentToModify">The document you want to modify.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
bool UpdateOne<TDocument, TField>(TDocument documentToModify, Expression<Func<TDocument, TField>> field, TField value)
where TDocument : IDocument;
/// <summary>
/// Updates the property field with the given value update a property field in entities.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="documentToModify">The document you want to modify.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
Task<bool> UpdateOneAsync<TDocument, TField>(TDocument documentToModify, Expression<Func<TDocument, TField>> field, TField value)
where TDocument : IDocument;
/// <summary>
/// For the entity selected by the filter, updates the property field with the given value.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="filter">The document filter.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
/// <param name="partitionKey">The partition key for the document.</param>
bool UpdateOne<TDocument, TField>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TField>> field, TField value, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Takes a document you want to modify and applies the update you have defined in MongoDb.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="documentToModify">The document you want to modify.</param>
/// <param name="update">The update definition for the document.</param>
Task<bool> UpdateOneAsync<TDocument>(TDocument documentToModify, UpdateDefinition<TDocument> update)
where TDocument : IDocument;
/// <summary>
/// For the entity selected by the filter, updates the property field with the given value.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="filter">The document filter.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
/// <param name="partitionKey">The partition key for the document.</param>
Task<bool> UpdateOneAsync<TDocument, TField>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TField>> field, TField value, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Takes a document you want to modify and applies the update you have defined in MongoDb.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="documentToModify">The document you want to modify.</param>
/// <param name="update">The update definition for the document.</param>
bool UpdateOne<TDocument>(TDocument documentToModify, UpdateDefinition<TDocument> update)
where TDocument : IDocument;
#endregion
#region Update TKey
/// <summary>
/// Asynchronously Updates a document.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="modifiedDocument">The document with the modifications you want to persist.</param>
Task<bool> UpdateOneAsync<TDocument, TKey>(TDocument modifiedDocument)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Updates a document.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="modifiedDocument">The document with the modifications you want to persist.</param>
bool UpdateOne<TDocument, TKey>(TDocument modifiedDocument)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Takes a document you want to modify and applies the update you have defined in MongoDb.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="documentToModify">The document you want to modify.</param>
/// <param name="update">The update definition for the document.</param>
Task<bool> UpdateOneAsync<TDocument, TKey>(TDocument documentToModify, UpdateDefinition<TDocument> update)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Takes a document you want to modify and applies the update you have defined in MongoDb.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="documentToModify">The document you want to modify.</param>
/// <param name="update">The update definition for the document.</param>
bool UpdateOne<TDocument, TKey>(TDocument documentToModify, UpdateDefinition<TDocument> update)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// For the entity selected by the filter, updates the property field with the given value..
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="filter">The document filter.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
/// <param name="partitionKey">The partition key for the document.</param>
bool UpdateOne<TDocument, TKey, TField>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TField>> field, TField value, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Updates the property field with the given value update a property field in entities.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="documentToModify">The document you want to modify.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
Task<bool> UpdateOneAsync<TDocument, TKey, TField>(TDocument documentToModify, Expression<Func<TDocument, TField>> field, TField value)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// For the entity selected by the filter, updates the property field with the given value.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="filter">The document filter.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
/// <param name="partitionKey">The partition key for the document.</param>
Task<bool> UpdateOneAsync<TDocument, TKey, TField>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TField>> field, TField value, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Updates the property field with the given value update a property field in entities.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="documentToModify">The document you want to modify.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
bool UpdateOne<TDocument, TKey, TField>(TDocument documentToModify, Expression<Func<TDocument, TField>> field, TField value)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Updates the property field with the given value update a property field in entities.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="filter">The document filter.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
/// <param name="partitionKey">The value of the partition key.</param>
Task<bool> UpdateOneAsync<TDocument, TKey, TField>(FilterDefinition<TDocument> filter, Expression<Func<TDocument, TField>> field, TField value, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Updates the property field with the given value update a property field in entities.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="filter">The document filter.</param>
/// <param name="field">The field selector.</param>
/// <param name="value">The new value of the property field.</param>
/// <param name="partitionKey">The value of the partition key.</param>
bool UpdateOne<TDocument, TKey, TField>(FilterDefinition<TDocument> filter, Expression<Func<TDocument, TField>> field, TField value, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
#endregion
#region Delete
/// <summary>
/// Asynchronously deletes a document.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="document">The document you want to delete.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteOneAsync<TDocument>(TDocument document) where TDocument : IDocument;
/// <summary>
/// Asynchronously deletes a document matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteOneAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Deletes a document.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="document">The document you want to delete.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteOne<TDocument>(TDocument document) where TDocument : IDocument;
/// <summary>
/// Deletes a document matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteOne<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously deletes the documents matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteManyAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously deletes a list of documents.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="documents">The list of documents to delete.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteManyAsync<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument;
/// <summary>
/// Deletes a list of documents.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="documents">The list of documents to delete.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteMany<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument;
/// <summary>
/// Deletes the documents matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteMany<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
#endregion
#region Delete TKey
/// <summary>
/// Deletes a document.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="document">The document you want to delete.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteOne<TDocument, TKey>(TDocument document)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Asynchronously deletes a document matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="document">The document you want to delete.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteOneAsync<TDocument, TKey>(TDocument document)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Deletes a document matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteOne<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Asynchronously deletes a document matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteOneAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Asynchronously deletes the documents matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteManyAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Asynchronously deletes a list of documents.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="documents">The list of documents to delete.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteManyAsync<TDocument, TKey>(IEnumerable<TDocument> documents)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Deletes a list of documents.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="documents">The list of documents to delete.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteMany<TDocument, TKey>(IEnumerable<TDocument> documents)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Deletes the documents matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteMany<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
#endregion
#region Project
/// <summary>
/// Asynchronously returns a projected document matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TProjection">The type representing the model you want to project to.</typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TProjection> ProjectOneAsync<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class;
/// <summary>
/// Asynchronously returns a projected document matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TProjection">The type representing the model you want to project to.</typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TProjection> ProjectOneAsync<TDocument, TProjection, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
where TProjection : class;
/// <summary>
/// Returns a projected document matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TProjection">The type representing the model you want to project to.</typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
TProjection ProjectOne<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class;
/// <summary>
/// Returns a projected document matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TProjection">The type representing the model you want to project to.</typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
TProjection ProjectOne<TDocument, TProjection, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
where TProjection : class;
/// <summary>
/// Asynchronously returns a list of projected documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TProjection">The type representing the model you want to project to.</typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<List<TProjection>> ProjectManyAsync<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class;
/// <summary>
/// Asynchronously returns a list of projected documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TProjection">The type representing the model you want to project to.</typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<List<TProjection>> ProjectManyAsync<TDocument, TProjection, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
where TProjection : class;
/// <summary>
/// Asynchronously returns a list of projected documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TProjection">The type representing the model you want to project to.</typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
List<TProjection> ProjectMany<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class;
/// <summary>
/// Asynchronously returns a list of projected documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <typeparam name="TProjection">The type representing the model you want to project to.</typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
List<TProjection> ProjectMany<TDocument, TProjection, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
where TProjection : class;
#endregion
/// <summary>
/// Asynchronously returns a paginated list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter"></param>
/// <param name="skipNumber">The number of documents you want to skip. Default value is 0.</param>
/// <param name="takeNumber">The number of documents you want to take. Default value is 50.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<List<TDocument>> GetPaginatedAsync<TDocument>(Expression<Func<TDocument, bool>> filter, int skipNumber = 0, int takeNumber = 50, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Asynchronously returns a paginated list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter"></param>
/// <param name="skipNumber">The number of documents you want to skip. Default value is 0.</param>
/// <param name="takeNumber">The number of documents you want to take. Default value is 50.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<List<TDocument>> GetPaginatedAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, int skipNumber = 0, int takeNumber = 50, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// GetAndUpdateOne with filter
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter"></param>
/// <param name="update"></param>
/// <param name="options"></param>
/// <returns></returns>
Task<TDocument> GetAndUpdateOne<TDocument>(FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, FindOneAndUpdateOptions<TDocument, TDocument> options)
where TDocument : IDocument;
/// <summary>
/// GetAndUpdateOne with filter
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter"></param>
/// <param name="update"></param>
/// <param name="options"></param>
/// <returns></returns>
Task<TDocument> GetAndUpdateOne<TDocument, TKey>(FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, FindOneAndUpdateOptions<TDocument, TDocument> options)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
#region Grouping
/// <summary>
/// Groups a collection of documents given a grouping criteria,
/// and returns a list of projected documents.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TGroupKey">The type of the grouping criteria.</typeparam>
/// <typeparam name="TProjection">The type of the projected group.</typeparam>
/// <param name="groupingCriteria">The grouping criteria.</param>
/// <param name="groupProjection">The projected group result.</param>
/// <param name="partitionKey">The partition key of your document, if any.</param>
List<TProjection> GroupBy<TDocument, TGroupKey, TProjection>(
Expression<Func<TDocument, TGroupKey>> groupingCriteria,
Expression<Func<IGrouping<TGroupKey, TDocument>, TProjection>> groupProjection,
string partitionKey = null)
where TDocument : IDocument
where TProjection : class, new();
/// <summary>
/// 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.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TGroupKey">The type of the grouping criteria.</typeparam>
/// <typeparam name="TProjection">The type of the projected group.</typeparam>
/// <param name="filter"></param>
/// <param name="selector">The grouping criteria.</param>
/// <param name="projection">The projected group result.</param>
/// <param name="partitionKey">The partition key of your document, if any.</param>
List<TProjection> GroupBy<TDocument, TGroupKey, TProjection>(Expression<Func<TDocument, bool>> filter,
Expression<Func<TDocument, TGroupKey>> selector,
Expression<Func<IGrouping<TGroupKey, TDocument>, TProjection>> projection,
string partitionKey = null)
where TDocument : IDocument
where TProjection : class, new();
#endregion
}
}
@@ -0,0 +1,41 @@
using MongoDB.Driver;
using MongoDbGenericRepository.Models;
using System;
namespace MongoDbGenericRepository
{
/// <summary>
/// This is the interface of the IMongoDbContext which is managed by the <see cref="BaseMongoRepository"/>.
/// </summary>
public interface IMongoDbContext
{
/// <summary>
/// The IMongoClient from the official MongoDb driver
/// </summary>
IMongoClient Client { get; }
/// <summary>
/// The IMongoDatabase from the official Mongodb driver
/// </summary>
IMongoDatabase Database { get; }
/// <summary>
/// Returns a collection for a document type that has a partition key.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="partitionKey">The value of the partition key.</param>
IMongoCollection<TDocument> GetCollection<TDocument>(string partitionKey = null);
/// <summary>
/// Drops a collection having a partitionkey, use very carefully.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
void DropCollection<TDocument>(string partitionKey = null);
/// <summary>
/// Sets the Guid representation of the MongoDb Driver.
/// </summary>
/// <param name="guidRepresentation">The new value of the GuidRepresentation</param>
void SetGuidRepresentation(MongoDB.Bson.GuidRepresentation guidRepresentation);
}
}
@@ -0,0 +1,430 @@
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq.Expressions;
using MongoDbGenericRepository.Models;
namespace MongoDbGenericRepository
{
/// <summary>
/// The IReadOnlyMongoRepository exposes the readonly functionality of the BaseMongoRepository.
/// </summary>
public interface IReadOnlyMongoRepository
{
/// <summary>
/// The connection string.
/// </summary>
string ConnectionString { get; set; }
/// <summary>
/// The database name.
/// </summary>
string DatabaseName { get; set; }
#region Read
/// <summary>
/// Asynchronously returns one document given its id.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TDocument> GetByIdAsync<TDocument>(Guid id, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns one document given its id.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
TDocument GetById<TDocument>(Guid id, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TDocument> GetOneAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
TDocument GetOne<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns a collection cursor.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
IFindFluent<TDocument, TDocument> GetCursor<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<bool> AnyAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
bool Any<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<List<TDocument>> GetAllAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
List<TDocument> GetAll<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<long> CountAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
long Count<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
#endregion
#region Read TKey
/// <summary>
/// Asynchronously returns one document given its id.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TDocument> GetByIdAsync<TDocument, TKey>(TKey id, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Returns one document given its id.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
TDocument GetById<TDocument, TKey>(TKey id, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Asynchronously returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TDocument> GetOneAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
TDocument GetOne<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Returns a collection cursor.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
IFindFluent<TDocument, TDocument> GetCursor<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<bool> AnyAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
bool Any<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Asynchronously returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<List<TDocument>> GetAllAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
List<TDocument> GetAll<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Asynchronously counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partitionKey</param>
Task<long> CountAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partitionKey</param>
long Count<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
#endregion
#region Min / Max
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByDescending">A property selector to order by descending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
Task<TDocument> GetByMaxAsync<TDocument>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByDescending, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByDescending">A property selector to order by descending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
/// <returns></returns>
TDocument GetByMax<TDocument>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByDescending, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
Task<TDocument> GetByMinAsync<TDocument>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByAscending, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
TDocument GetByMin<TDocument>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByAscending, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by descending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
Task<TDocument> GetByMaxAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByDescending, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by descending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
TDocument GetByMax<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByDescending, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
Task<TDocument> GetByMinAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByAscending, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
TDocument GetByMin<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByAscending, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Gets the maximum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
Task<TValue> GetMaxValueAsync<TDocument, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Gets the maximum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
Task<TValue> GetMaxValueAsync<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Gets the maximum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
TValue GetMaxValue<TDocument, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Gets the maximum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
TValue GetMaxValue<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> orderByDescending, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TValue> GetMinValueAsync<TDocument, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> minValueSelector, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TValue> GetMinValueAsync<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> minValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partition key.</param>
TValue GetMinValue<TDocument, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> minValueSelector, string partitionKey = null)
where TDocument : IDocument;
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partition key.</param>
TValue GetMinValue<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> minValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>;
#endregion
}
}
@@ -1,3 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
</ApplicationInsights>
@@ -0,0 +1,29 @@
using System;
namespace MongoDbGenericRepository.Attributes
{
/// <summary>
/// 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.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class CollectionNameAttribute : Attribute
{
/// <summary>
/// The name of the collection in which your documents are stored.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The constructor.
/// </summary>
/// <param name="name">The name of the collection.</param>
public CollectionNameAttribute(string name)
{
this.Name = name;
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,33 +0,0 @@
using MongoDB.Driver;
using MongoDbGenericRepository.Models;
namespace MongoDbGenericRepository
{
public interface IMongoDbContext
{
/// <summary>
/// The private GetCollection method
/// </summary>
/// <typeparam name="TDocument"></typeparam>
IMongoCollection<TDocument> GetCollection<TDocument>();
/// <summary>
/// Returns a collection for a document type that has a partition key.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="partitionKey">The value of the partition key.</param>
IMongoCollection<TDocument> GetCollection<TDocument>(string partitionKey) where TDocument : IDocument;
/// <summary>
/// Drops a collection, use very carefully.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
void DropCollection<TDocument>();
/// <summary>
/// Drops a collection having a partitionkey, use very carefully.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
void DropCollection<TDocument>(string partitionKey);
}
}
+2 -15
View File
@@ -4,7 +4,8 @@ using System;
namespace MongoDbGenericRepository.Models
{
/// <summary>
/// This class represents a basic document that can be stored in MongoDb
/// 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.
/// </summary>
public class Document : IDocument
{
@@ -33,18 +34,4 @@ namespace MongoDbGenericRepository.Models
/// </summary>
public int Version { get; set; }
}
public class PartitionedDocument : Document, IPartitionedDocument
{
public PartitionedDocument(string partitionKey)
{
PartitionKey = partitionKey;
}
/// <summary>
/// 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.
/// </summary>
public string PartitionKey { get; set; }
}
}
+14 -10
View File
@@ -1,4 +1,5 @@
using System;
using MongoDB.Bson.Serialization.Attributes;
using System;
namespace MongoDbGenericRepository.Models
{
@@ -6,21 +7,24 @@ 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.
/// </summary>
public interface IDocument
public interface IDocument<TKey> where TKey : IEquatable<TKey>
{
DateTime AddedAtUtc { get; set; }
Guid Id { get; set; }
/// <summary>
/// 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.
/// </summary>
TKey Id { get; set; }
/// <summary>
/// A version number, to indicate the version of the schema.
/// </summary>
int Version { get; set; }
}
/// <summary>
/// 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.
/// 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.
/// </summary>
public interface IPartitionedDocument : IDocument
public interface IDocument : IDocument<Guid>
{
string PartitionKey { get; set; }
}
}
@@ -0,0 +1,16 @@
namespace MongoDbGenericRepository.Models
{
/// <summary>
/// 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.
/// </summary>
public interface IPartitionedDocument
{
/// <summary>
/// The partition key used to partition your collection.
/// </summary>
string PartitionKey { get; set; }
}
}
@@ -0,0 +1,26 @@
namespace MongoDbGenericRepository.Models
{
/// <summary>
/// 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.
/// </summary>
public class PartitionedDocument : Document, IPartitionedDocument
{
/// <summary>
/// The constructor, it needs a partition key.
/// </summary>
/// <param name="partitionKey"></param>
public PartitionedDocument(string partitionKey)
{
PartitionKey = partitionKey;
}
/// <summary>
/// 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.
/// </summary>
public string PartitionKey { get; set; }
}
}
+77 -27
View File
@@ -1,5 +1,8 @@
using MongoDB.Driver;
using MongoDbGenericRepository.Models;
using MongoDbGenericRepository.Attributes;
using MongoDbGenericRepository.Utils;
using System.Linq;
using System.Reflection;
namespace MongoDbGenericRepository
{
@@ -8,67 +11,114 @@ namespace MongoDbGenericRepository
/// </summary>
public class MongoDbContext : IMongoDbContext
{
private readonly IMongoClient _client;
private readonly IMongoDatabase _database;
/// <summary>
/// The IMongoClient from the official MongoDb driver
/// </summary>
public IMongoClient Client { get; }
static MongoDbContext()
/// <summary>
/// The IMongoDatabase from the official Mongodb driver
/// </summary>
public IMongoDatabase Database { get; }
/// <summary>
/// Sets the Guid representation of the MongoDb Driver.
/// </summary>
/// <param name="guidRepresentation">The new value of the GuidRepresentation</param>
public virtual void SetGuidRepresentation(MongoDB.Bson.GuidRepresentation guidRepresentation)
{
// Avoid legacy UUID representation: use Binary 0x04 subtype.
MongoDefaults.GuidRepresentation = guidRepresentation;
}
/// <summary>
/// Initialize the Guid representation of the MongoDb Driver.
/// Override this method to change the default GuidRepresentation.
/// </summary>
protected virtual void InitializeGuidRepresentation()
{
// by default, avoid lefacy UUID representation: use Binary 0x04 subtype.
MongoDefaults.GuidRepresentation = MongoDB.Bson.GuidRepresentation.Standard;
}
/// <summary>
/// The constructor of the MongoDbContext, it needs a an object implementing <see cref="IMongoDatabase"/>.
/// </summary>
/// <param name="mongoDatabase">An object implementing IMongoDatabase</param>
public MongoDbContext(IMongoDatabase mongoDatabase)
{
// Avoid legacy UUID representation: use Binary 0x04 subtype.
InitializeGuidRepresentation();
Database = mongoDatabase;
Client = Database.Client;
}
/// <summary>
/// The constructor of the MongoDbContext, it needs a connection string and a database name.
/// </summary>
/// <param name="connectionString">The connections string.</param>
/// <param name="databaseName">The name of your database.</param>
public MongoDbContext(string connectionString, string databaseName)
{
_client = new MongoClient(connectionString);
_database = _client.GetDatabase(databaseName);
InitializeGuidRepresentation();
Client = new MongoClient(connectionString);
Database = Client.GetDatabase(databaseName);
}
/// <summary>
/// The private GetCollection method
/// Extracts the CollectionName attribute from the entity type, if any.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <returns></returns>
public IMongoCollection<TDocument> GetCollection<TDocument>()
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <returns>The name of the collection in which the TDocument is stored.</returns>
private string GetAttributeCollectionName<TDocument>()
{
return _database.GetCollection<TDocument>(Pluralize<TDocument>());
return (typeof(TDocument).GetTypeInfo()
.GetCustomAttributes(typeof(CollectionNameAttribute))
.FirstOrDefault() as CollectionNameAttribute)?.Name;
}
/// <summary>
/// Returns a collection for a document type that has a partition key.
/// Returns a collection for a document type. Also handles document types with a partition key.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="partitionKey">The value of the partition key.</param>
public IMongoCollection<TDocument> GetCollection<TDocument>(string partitionKey) where TDocument : IDocument
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="partitionKey">The optional value of the partition key.</param>
public IMongoCollection<TDocument> GetCollection<TDocument>(string partitionKey = null)
{
return _database.GetCollection<TDocument>(partitionKey +"-"+ Pluralize<TDocument>());
return Database.GetCollection<TDocument>(GetCollectionName<TDocument>(partitionKey));
}
/// <summary>
/// Drops a collection, use very carefully.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
public void DropCollection<TDocument>()
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
public void DropCollection<TDocument>(string partitionKey = null)
{
_database.DropCollection(Pluralize<TDocument>());
Database.DropCollection(GetCollectionName<TDocument>(partitionKey));
}
/// <summary>
/// Drops a collection having a partitionkey, use very carefully.
/// Given the docmuent type and the partition key, returns the name of the collection it belongs to.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
public void DropCollection<TDocument>(string partitionKey)
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="partitionKey">The value of the partition key.</param>
/// <returns>The name of the collection.</returns>
private string GetCollectionName<TDocument>(string partitionKey)
{
_database.DropCollection(partitionKey + "-" + Pluralize<TDocument>());
var collectionName = GetAttributeCollectionName<TDocument>() ?? Pluralize<TDocument>();
if (string.IsNullOrEmpty(partitionKey))
{
return collectionName;
}
return $"{partitionKey}-{collectionName}";
}
/// <summary>
/// Very naively pluralizes a TDocument type name.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <returns></returns>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <returns>The pluralized document name.</returns>
private string Pluralize<TDocument>()
{
return typeof(TDocument).Name.ToLower() + "s";
return (typeof(TDocument).Name.Pluralize()).Camelize();
}
}
}
@@ -1,141 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.2.3.1\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.2.3.1\build\Microsoft.Net.Compilers.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{D154E7D0-9A3C-43AB-8E90-ED92BC4343F0}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MongoDbGenericRepository</RootNamespace>
<AssemblyName>MongoDbGenericRepository</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<UseIISExpress>true</UseIISExpress>
<IISExpressSSLPort />
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<UseGlobalApplicationHostFile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworks>net45;netstandard1.5;netstandard2.0</TargetFrameworks>
<PackageId>MongoDbGenericRepository</PackageId>
<PackageVersion>1.2.0</PackageVersion>
<Authors>Alexandre Spieser</Authors>
<Description>A generic repository implementation using the MongoDB C# Sharp 2.0 driver.</Description>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<PackageReleaseNotes>.NET Core supported.</PackageReleaseNotes>
<Copyright>Copyright 2017 (c) Alexandre Spieser. All rights reserved.</Copyright>
<PackageTags>MongoDb Repository NoSql Generic</PackageTags>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net45|AnyCPU'">
<DocumentationFile>bin\Release\net45\MongoDbGenericRepository.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="MongoDB.Bson, Version=2.4.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Bson.2.4.4\lib\net45\MongoDB.Bson.dll</HintPath>
</Reference>
<Reference Include="MongoDB.Driver, Version=2.4.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Driver.2.4.4\lib\net45\MongoDB.Driver.dll</HintPath>
</Reference>
<Reference Include="MongoDB.Driver.Core, Version=2.4.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Driver.Core.2.4.4\lib\net45\MongoDB.Driver.Core.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
</Reference>
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Core" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Xml" />
<Reference Include="System.Configuration" />
<Reference Include="System.Web.Services" />
<Reference Include="System.EnterpriseServices" />
<PackageReference Include="MongoDB.Driver" Version="2.7.0" />
</ItemGroup>
<ItemGroup>
<Content Include="packages.config" />
<Content Include="ApplicationInsights.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="Web.Debug.config">
<DependentUpon>Web.config</DependentUpon>
</None>
<None Include="Web.Release.config">
<DependentUpon>Web.config</DependentUpon>
</None>
</ItemGroup>
<ItemGroup>
<Content Include="Web.config" />
</ItemGroup>
<ItemGroup>
<Compile Include="IMongoDbContext.cs" />
<Compile Include="Models\Document.cs" />
<Compile Include="Models\IDocument.cs" />
<Compile Include="MongoDbContext.cs" />
<Compile Include="MongoDbRepository.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>52313</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:52313/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>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}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.2.3.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.2.3.1\build\Microsoft.Net.Compilers.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -1,31 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<UseIISExpress>true</UseIISExpress>
<ShowAllFiles>true</ShowAllFiles>
</PropertyGroup>
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<StartPageUrl>
</StartPageUrl>
<StartAction>CurrentPage</StartAction>
<AspNetDebugging>True</AspNetDebugging>
<SilverlightDebugging>False</SilverlightDebugging>
<NativeDebugging>False</NativeDebugging>
<SQLDebugging>False</SQLDebugging>
<ExternalProgram>
</ExternalProgram>
<StartExternalURL>
</StartExternalURL>
<StartCmdLineArguments>
</StartCmdLineArguments>
<StartWorkingDirectory>
</StartWorkingDirectory>
<EnableENC>True</EnableENC>
<AlwaysStartWebServerOnDebug>True</AlwaysStartWebServerOnDebug>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
</Project>
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<package >
<metadata>
<id>MongoDbGenericRepository</id>
<version>1.3.7</version>
<title>MongoDb Generic Repository</title>
<authors>Alexandre Spieser</authors>
<owners>Alexandre Spieser</owners>
<licenseUrl>http://www.opensource.org/licenses/mit-license.php</licenseUrl>
<projectUrl>https://github.com/alexandre-spieser/mongodb-generic-repository</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>A generic repository implementation using the MongoDB C# Sharp 2.0 driver.</description>
<releaseNotes>Upgraded dependencies. Full support for bulk insertion and deletion of documents of the same type but with different partitionkey values. Added methods for Min and Max queries.</releaseNotes>
<copyright>Copyright 2018 (c) Alexandre Spieser. All rights reserved.</copyright>
<tags>MongoDb Repository Generic NoSql</tags>
<dependencies>
<dependency id="MongoDB.Driver" version="2.7.0" />
</dependencies>
</metadata>
<files>
<file src="lib\**" target="lib" />
</files>
</package>
@@ -0,0 +1,752 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>MongoDbGenericRepository</name>
</assembly>
<members>
<member name="M:MongoDbGenericRepository.IMongoDbContext.GetCollection``1">
<summary>
The private GetCollection method
</summary>
<typeparam name="TDocument"></typeparam>
</member>
<member name="M:MongoDbGenericRepository.IMongoDbContext.GetCollection``1(System.String)">
<summary>
Returns a collection for a document type that has a partition key.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="partitionKey">The value of the partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IMongoDbContext.DropCollection``1">
<summary>
Drops a collection, use very carefully.
</summary>
<typeparam name="TDocument"></typeparam>
</member>
<member name="M:MongoDbGenericRepository.IMongoDbContext.DropCollection``1(System.String)">
<summary>
Drops a collection having a partitionkey, use very carefully.
</summary>
<typeparam name="TDocument"></typeparam>
</member>
<member name="T:MongoDbGenericRepository.Models.Document">
<summary>
This class represents a basic document that can be stored in MongoDb
</summary>
</member>
<member name="M:MongoDbGenericRepository.Models.Document.#ctor">
<summary>
The document constructor
</summary>
</member>
<member name="P:MongoDbGenericRepository.Models.Document.Id">
<summary>
The Id of the document
</summary>
</member>
<member name="P:MongoDbGenericRepository.Models.Document.AddedAtUtc">
<summary>
The datetime in UTC at which the document was added.
</summary>
</member>
<member name="P:MongoDbGenericRepository.Models.Document.Version">
<summary>
The version of the schema of the document
</summary>
</member>
<member name="P:MongoDbGenericRepository.Models.PartitionedDocument.PartitionKey">
<summary>
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.
</summary>
</member>
<member name="T:MongoDbGenericRepository.Models.IDocument">
<summary>
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.
</summary>
</member>
<member name="T:MongoDbGenericRepository.Models.IPartitionedDocument">
<summary>
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.
</summary>
</member>
<member name="T:MongoDbGenericRepository.MongoDbContext">
<summary>
The MongoDb context
</summary>
</member>
<member name="M:MongoDbGenericRepository.MongoDbContext.GetCollection``1">
<summary>
The private GetCollection method
</summary>
<typeparam name="TDocument"></typeparam>
<returns></returns>
</member>
<member name="M:MongoDbGenericRepository.MongoDbContext.GetCollection``1(System.String)">
<summary>
Returns a collection for a document type that has a partition key.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="partitionKey">The value of the partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.MongoDbContext.DropCollection``1">
<summary>
Drops a collection, use very carefully.
</summary>
<typeparam name="TDocument"></typeparam>
</member>
<member name="M:MongoDbGenericRepository.MongoDbContext.DropCollection``1(System.String)">
<summary>
Drops a collection having a partitionkey, use very carefully.
</summary>
<typeparam name="TDocument"></typeparam>
</member>
<member name="M:MongoDbGenericRepository.MongoDbContext.Pluralize``1">
<summary>
Very naively pluralizes a TDocument type name.
</summary>
<typeparam name="TDocument"></typeparam>
<returns></returns>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.AddOneAsync``1(``0)">
<summary>
Asynchronously adds a document to the collection.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="document">The document you want to add.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.AddOne``1(``0)">
<summary>
Adds a document to the collection.
Populates the Id and AddedAtUtc fields if necessary.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="document">The document you want to add.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.AddManyAsync``1(System.Collections.Generic.IEnumerable{``0})">
<summary>
Asynchronously adds a list of documents to the collection.
Populates the Id and AddedAtUtc fields if necessary.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="document">The document you want to add.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.AddMany``1(System.Collections.Generic.IEnumerable{``0})">
<summary>
Adds a list of documents to the collection.
Populates the Id and AddedAtUtc fields if necessary.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="document">The document you want to add.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.GetByIdAsync``1(System.Guid,System.String)">
<summary>
Asynchronously returns one document given its id.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="id">The Id of the document you want to get.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.GetById``1(System.Guid,System.String)">
<summary>
Returns one document given its id.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="id">The Id of the document you want to get.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.GetOneAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously returns one document given an expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.GetOne``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Returns one document given an expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.GetCursor``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Returns a collection cursor.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.AnyAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously returns true if any of the document of the collection matches the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.Any``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Returns true if any of the document of the collection matches the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.GetAllAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously returns a list of the documents matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.GetAll``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Returns a list of the documents matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.CountAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously counts how many documents match the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.Count``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Counts how many documents match the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.UpdateOneAsync``1(``0)">
<summary>
Asynchronously Updates a document.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="modifiedDocument">The document with the modifications you want to persist.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.UpdateOne``1(``0)">
<summary>
Updates a document.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="modifiedDocument">The document with the modifications you want to persist.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.DeleteOneAsync``1(``0)">
<summary>
Asynchronously deletes a document.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="TDocument">The document you want to delete.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.DeleteOneAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously deletes a document matching the condition of the LINQ expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.DeleteOne``1(``0)">
<summary>
Deletes a document.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="TDocument">The document you want to delete.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.DeleteOne``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Deletes a document matching the condition of the LINQ expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.DeleteManyAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously deletes the documents matching the condition of the LINQ expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.DeleteManyAsync``1(System.Collections.Generic.IEnumerable{``0})">
<summary>
Asynchronously deletes a list of documents.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="documents">The list of documents to delete.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.DeleteMany``1(System.Collections.Generic.IEnumerable{``0})">
<summary>
Deletes a list of documents.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="documents">The list of documents to delete.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.DeleteMany``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Deletes the documents matching the condition of the LINQ expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.ProjectOneAsync``2(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Linq.Expressions.Expression{System.Func{``0,``1}},System.String)">
<summary>
Asynchronously returns a projected document matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<typeparam name="TProjection"></typeparam>
<param name="filter"></param>
<param name="projection">The projection expression.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.ProjectOne``2(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Linq.Expressions.Expression{System.Func{``0,``1}},System.String)">
<summary>
Returns a projected document matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<typeparam name="TProjection"></typeparam>
<param name="filter"></param>
<param name="projection">The projection expression.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.ProjectManyAsync``2(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Linq.Expressions.Expression{System.Func{``0,``1}},System.String)">
<summary>
Asynchronously returns a list of projected documents matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<typeparam name="TProjection"></typeparam>
<param name="filter"></param>
<param name="projection">The projection expression.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.IBaseMongoRepository.ProjectMany``2(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Linq.Expressions.Expression{System.Func{``0,``1}},System.String)">
<summary>
Asynchronously returns a list of projected documents matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<typeparam name="TProjection"></typeparam>
<param name="filter"></param>
<param name="projection">The projection expression.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="T:MongoDbGenericRepository.BaseMongoRepository">
<summary>
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.
</summary>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.#ctor(System.String,System.String)">
<summary>
The base constructor
</summary>
<param name="connectionString">The connection string of the MongoDb server.</param>
<param name="databaseName">The name of the database against which you want to perform operations.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.AddOneAsync``1(``0)">
<summary>
Asynchronously adds a document to the collection.
Populates the Id and AddedAtUtc fields if necessary.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="document">The document you want to add.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.AddOne``1(``0)">
<summary>
Adds a document to the collection.
Populates the Id and AddedAtUtc fields if necessary.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="document">The document you want to add.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.AddManyAsync``1(System.Collections.Generic.IEnumerable{``0})">
<summary>
Asynchronously adds a list of documents to the collection.
Populates the Id and AddedAtUtc fields if necessary.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="document">The document you want to add.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.AddMany``1(System.Collections.Generic.IEnumerable{``0})">
<summary>
Adds a list of documents to the collection.
Populates the Id and AddedAtUtc fields if necessary.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="document">The document you want to add.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.GetByIdAsync``1(System.Guid,System.String)">
<summary>
Asynchronously returns one document given its id.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="id">The Id of the document you want to get.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.GetById``1(System.Guid,System.String)">
<summary>
Returns one document given its id.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="id">The Id of the document you want to get.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.GetOneAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously returns one document given an expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.GetOne``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Returns one document given an expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.GetCursor``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Returns a collection cursor.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.AnyAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Returns true if any of the document of the collection matches the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.Any``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Returns true if any of the document of the collection matches the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.GetAllAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously returns a list of the documents matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.GetAll``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Returns a list of the documents matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.CountAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously counts how many documents match the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partitionKey</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.Count``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Counts how many documents match the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partitionKey</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.UpdateOneAsync``1(``0)">
<summary>
Asynchronously Updates a document.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="modifiedDocument">The document with the modifications you want to persist.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.UpdateOne``1(``0)">
<summary>
Updates a document.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="modifiedDocument">The document with the modifications you want to persist.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.DeleteOneAsync``1(``0)">
<summary>
Asynchronously deletes a document.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="TDocument">The document you want to delete.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.DeleteOne``1(``0)">
<summary>
Deletes a document.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="TDocument">The document you want to delete.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.DeleteOne``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Deletes a document matching the condition of the LINQ expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.DeleteOneAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously deletes a document matching the condition of the LINQ expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.DeleteManyAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Asynchronously deletes the documents matching the condition of the LINQ expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.DeleteManyAsync``1(System.Collections.Generic.IEnumerable{``0})">
<summary>
Asynchronously deletes a list of documents.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="documents">The list of documents to delete.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.DeleteMany``1(System.Collections.Generic.IEnumerable{``0})">
<summary>
Deletes a list of documents.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="documents">The list of documents to delete.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.DeleteMany``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.String)">
<summary>
Deletes the documents matching the condition of the LINQ expression filter.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter">A LINQ expression filter.</param>
<param name="partitionKey">An optional partition key.</param>
<returns>The number of documents deleted.</returns>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.ProjectOneAsync``2(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Linq.Expressions.Expression{System.Func{``0,``1}},System.String)">
<summary>
Asynchronously returns a projected document matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<typeparam name="TProjection"></typeparam>
<param name="filter"></param>
<param name="projection">The projection expression.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.ProjectOne``2(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Linq.Expressions.Expression{System.Func{``0,``1}},System.String)">
<summary>
Returns a projected document matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<typeparam name="TProjection"></typeparam>
<param name="filter"></param>
<param name="projection">The projection expression.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.ProjectManyAsync``2(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Linq.Expressions.Expression{System.Func{``0,``1}},System.String)">
<summary>
Asynchronously returns a list of projected documents matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<typeparam name="TProjection"></typeparam>
<param name="filter"></param>
<param name="projection">The projection expression.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.ProjectMany``2(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Linq.Expressions.Expression{System.Func{``0,``1}},System.String)">
<summary>
Asynchronously returns a list of projected documents matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<typeparam name="TProjection"></typeparam>
<param name="filter"></param>
<param name="projection">The projection expression.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.GetPaginatedAsync``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Int32,System.Int32,System.String)">
<summary>
Asynchronously returns a paginated list of the documents matching the filter condition.
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter"></param>
<param name="skipNumber">The number of documents you want to skip. Default value is 0.</param>
<param name="takeNumber">The number of documents you want to take. Default value is 50.</param>
<param name="partitionKey">An optional partition key.</param>
</member>
<member name="M:MongoDbGenericRepository.BaseMongoRepository.GetAndUpdateOne``1(MongoDB.Driver.FilterDefinition{``0},MongoDB.Driver.UpdateDefinition{``0},MongoDB.Driver.FindOneAndUpdateOptions{``0,``0})">
<summary>
GetAndUpdateOne with filter
</summary>
<typeparam name="TDocument"></typeparam>
<param name="filter"></param>
<param name="update"></param>
<param name="options"></param>
<returns></returns>
</member>
<member name="T:MongoDbGenericRepository.Vocabularies">
<summary>
Container for registered Vocabularies. At present, only a single vocabulary is supported: Default.
</summary>
</member>
<member name="P:MongoDbGenericRepository.Vocabularies.Default">
<summary>
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.
</summary>
</member>
<member name="T:MongoDbGenericRepository.Vocabulary">
<summary>
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.
</summary>
</member>
<member name="M:MongoDbGenericRepository.Vocabulary.AddIrregular(System.String,System.String,System.Boolean)">
<summary>
Adds a word to the vocabulary which cannot easily be pluralized/singularized by RegEx, e.g. "person" and "people".
</summary>
<param name="singular">The singular form of the irregular word, e.g. "person".</param>
<param name="plural">The plural form of the irregular word, e.g. "people".</param>
<param name="matchEnding">True to match these words on their own as well as at the end of longer words. False, otherwise.</param>
</member>
<member name="M:MongoDbGenericRepository.Vocabulary.AddUncountable(System.String)">
<summary>
Adds an uncountable word to the vocabulary, e.g. "fish". Will be ignored when plurality is changed.
</summary>
<param name="word">Word to be added to the list of uncountables.</param>
</member>
<member name="M:MongoDbGenericRepository.Vocabulary.AddPlural(System.String,System.String)">
<summary>
Adds a rule to the vocabulary that does not follow trivial rules for pluralization, e.g. "bus" -> "buses"
</summary>
<param name="rule">RegEx to be matched, case insensitive, e.g. "(bus)es$"</param>
<param name="replacement">RegEx replacement e.g. "$1"</param>
</member>
<member name="M:MongoDbGenericRepository.Vocabulary.AddSingular(System.String,System.String)">
<summary>
Adds a rule to the vocabulary that does not follow trivial rules for singularization, e.g. "vertices/indices -> "vertex/index"
</summary>
<param name="rule">RegEx to be matched, case insensitive, e.g. ""(vert|ind)ices$""</param>
<param name="replacement">RegEx replacement e.g. "$1ex"</param>
</member>
<member name="M:MongoDbGenericRepository.Vocabulary.Pluralize(System.String,System.Boolean)">
<summary>
Pluralizes the provided input considering irregular words
</summary>
<param name="word">Word to be pluralized</param>
<param name="inputIsKnownToBeSingular">Normally you call Pluralize on singular words; but if you're unsure call it with false</param>
<returns></returns>
</member>
<member name="M:MongoDbGenericRepository.Vocabulary.Singularize(System.String,System.Boolean)">
<summary>
Singularizes the provided input considering irregular words
</summary>
<param name="word">Word to be singularized</param>
<param name="inputIsKnownToBePlural">Normally you call Singularize on plural words; but if you're unsure call it with false</param>
<returns></returns>
</member>
<member name="T:MongoDbGenericRepository.InflectorExtensions">
<summary>
Inflector extensions
</summary>
</member>
<member name="M:MongoDbGenericRepository.InflectorExtensions.Pluralize(System.String,System.Boolean)">
<summary>
Pluralizes the provided input considering irregular words
</summary>
<param name="word">Word to be pluralized</param>
<param name="inputIsKnownToBeSingular">Normally you call Pluralize on singular words; but if you're unsure call it with false</param>
<returns></returns>
</member>
<member name="M:MongoDbGenericRepository.InflectorExtensions.Singularize(System.String,System.Boolean)">
<summary>
Singularizes the provided input considering irregular words
</summary>
<param name="word">Word to be singularized</param>
<param name="inputIsKnownToBePlural">Normally you call Singularize on plural words; but if you're unsure call it with false</param>
<returns></returns>
</member>
<member name="M:MongoDbGenericRepository.InflectorExtensions.Pascalize(System.String)">
<summary>
By default, pascalize converts strings to UpperCamelCase also removing underscores
</summary>
<param name="input"></param>
<returns></returns>
</member>
<member name="M:MongoDbGenericRepository.InflectorExtensions.Camelize(System.String)">
<summary>
Same as Pascalize except that the first character is lower case
</summary>
<param name="input"></param>
<returns></returns>
</member>
<member name="M:MongoDbGenericRepository.InflectorExtensions.Underscore(System.String)">
<summary>
Separates the input words with underscore
</summary>
<param name="input">The string to be underscored</param>
<returns></returns>
</member>
<member name="M:MongoDbGenericRepository.InflectorExtensions.Dasherize(System.String)">
<summary>
Replaces underscores with dashes in the string
</summary>
<param name="underscoredWord"></param>
<returns></returns>
</member>
<member name="M:MongoDbGenericRepository.InflectorExtensions.Hyphenate(System.String)">
<summary>
Replaces underscores with hyphens in the string
</summary>
<param name="underscoredWord"></param>
<returns></returns>
</member>
</members>
</doc>
@@ -1,783 +0,0 @@
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq.Expressions;
using MongoDbGenericRepository.Models;
using System.Linq;
namespace MongoDbGenericRepository
{
public interface IBaseMongoRepository
{
#region Create
/// <summary>
/// Asynchronously adds a document to the collection.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="document">The document you want to add.</param>
Task AddOneAsync<TDocument>(TDocument document) where TDocument : IDocument;
/// <summary>
/// Adds a document to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="document">The document you want to add.</param>
void AddOne<TDocument>(TDocument document) where TDocument : IDocument;
/// <summary>
/// Asynchronously adds a list of documents to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="document">The document you want to add.</param>
Task AddManyAsync<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument;
/// <summary>
/// Adds a list of documents to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="document">The document you want to add.</param>
void AddMany<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument;
#endregion
#region Read
/// <summary>
/// Asynchronously returns one document given its id.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TDocument> GetByIdAsync<TDocument>(Guid id, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns one document given its id.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
TDocument GetById<TDocument>(Guid id, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TDocument> GetOneAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
TDocument GetOne<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns a collection cursor.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
IFindFluent<TDocument, TDocument> GetCursor<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<bool> AnyAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
bool Any<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<List<TDocument>> GetAllAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
List<TDocument> GetAll<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<long> CountAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
long Count<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
#endregion
#region Update
/// <summary>
/// Asynchronously Updates a document.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="modifiedDocument">The document with the modifications you want to persist.</param>
Task<bool> UpdateOneAsync<TDocument>(TDocument modifiedDocument) where TDocument : IDocument;
/// <summary>
/// Updates a document.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="modifiedDocument">The document with the modifications you want to persist.</param>
bool UpdateOne<TDocument>(TDocument modifiedDocument) where TDocument : IDocument;
#endregion
#region Delete
/// <summary>
/// Asynchronously deletes a document.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="TDocument">The document you want to delete.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteOneAsync<TDocument>(TDocument document) where TDocument : IDocument;
/// <summary>
/// Asynchronously deletes a document matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteOneAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Deletes a document.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="TDocument">The document you want to delete.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteOne<TDocument>(TDocument document) where TDocument : IDocument;
/// <summary>
/// Deletes a document matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteOne<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously deletes the documents matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteManyAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
/// <summary>
/// Asynchronously deletes a list of documents.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="documents">The list of documents to delete.</param>
/// <returns>The number of documents deleted.</returns>
Task<long> DeleteManyAsync<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument;
/// <summary>
/// Deletes a list of documents.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="documents">The list of documents to delete.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteMany<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument;
/// <summary>
/// Deletes the documents matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
long DeleteMany<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument;
#endregion
#region Project
/// <summary>
/// Asynchronously returns a projected document matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <typeparam name="TProjection"></typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<TProjection> ProjectOneAsync<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class;
/// <summary>
/// Returns a projected document matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <typeparam name="TProjection"></typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
TProjection ProjectOne<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class;
/// <summary>
/// Asynchronously returns a list of projected documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <typeparam name="TProjection"></typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
Task<List<TProjection>> ProjectManyAsync<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class;
/// <summary>
/// Asynchronously returns a list of projected documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <typeparam name="TProjection"></typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
List<TProjection> ProjectMany<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class;
#endregion
}
/// <summary>
/// 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.
/// </summary>
public abstract class BaseMongoRepository : IBaseMongoRepository
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
/// <summary>
/// The base constructor
/// </summary>
/// <param name="connectionString">The connection string of the MongoDb server.</param>
/// <param name="databaseName">The name of the database against which you want to perform operations.</param>
protected BaseMongoRepository(string connectionString, string databaseName)
{
_mongoDbContext = new MongoDbContext(connectionString, databaseName);
}
protected IMongoDbContext _mongoDbContext = null;
#region Create
/// <summary>
/// Asynchronously adds a document to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="document">The document you want to add.</param>
public async Task AddOneAsync<TDocument>(TDocument document) where TDocument : IDocument
{
FormatDocument(document);
await HandlePartitioned(document).InsertOneAsync(document);
}
/// <summary>
/// Adds a document to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="document">The document you want to add.</param>
public void AddOne<TDocument>(TDocument document) where TDocument : IDocument
{
FormatDocument(document);
HandlePartitioned(document).InsertOne(document);
}
/// <summary>
/// Asynchronously adds a list of documents to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="document">The document you want to add.</param>
public async Task AddManyAsync<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument
{
if (!documents.Any())
{
return;
}
foreach (var doc in documents)
{
FormatDocument(doc);
}
await HandlePartitioned(documents.FirstOrDefault()).InsertManyAsync(documents);
}
/// <summary>
/// Adds a list of documents to the collection.
/// Populates the Id and AddedAtUtc fields if necessary.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="document">The document you want to add.</param>
public void AddMany<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument
{
if (!documents.Any())
{
return;
}
foreach (var document in documents)
{
FormatDocument(document);
}
HandlePartitioned(documents.FirstOrDefault()).InsertMany(documents.ToList());
}
#endregion Create
#region Read
/// <summary>
/// Asynchronously returns one document given its id.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<TDocument> GetByIdAsync<TDocument>(Guid id, string partitionKey = null) where TDocument : IDocument
{
var filter = Builders<TDocument>.Filter.Eq("Id", id);
return await HandlePartitioned<TDocument>(partitionKey).Find(filter).FirstOrDefaultAsync();
}
/// <summary>
/// Returns one document given its id.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
public TDocument GetById<TDocument>(Guid id, string partitionKey = null) where TDocument : IDocument
{
var filter = Builders<TDocument>.Filter.Eq("Id", id);
return HandlePartitioned<TDocument>(partitionKey).Find(filter).FirstOrDefault();
}
/// <summary>
/// Asynchronously returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<TDocument> GetOneAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return await HandlePartitioned<TDocument>(partitionKey).Find(filter).FirstOrDefaultAsync();
}
/// <summary>
/// Returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public TDocument GetOne<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter).FirstOrDefault();
}
/// <summary>
/// Returns a collection cursor.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public IFindFluent<TDocument, TDocument> GetCursor<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter);
}
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<bool> AnyAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
var count = await HandlePartitioned<TDocument>(partitionKey).CountAsync(filter);
return (count > 0);
}
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public bool Any<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
var count = HandlePartitioned<TDocument>(partitionKey).Count(filter);
return (count > 0);
}
/// <summary>
/// Asynchronously returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<List<TDocument>> GetAllAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return await HandlePartitioned<TDocument>(partitionKey).Find(filter).ToListAsync();
}
/// <summary>
/// Returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public List<TDocument> GetAll<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter).ToList();
}
/// <summary>
/// Asynchronously counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partitionKey</param>
public async Task<long> CountAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return await HandlePartitioned<TDocument>(partitionKey).CountAsync(filter);
}
/// <summary>
/// Counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partitionKey</param>
public long Count<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter).Count();
}
#endregion
#region Update
/// <summary>
/// Asynchronously Updates a document.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="modifiedDocument">The document with the modifications you want to persist.</param>
public async Task<bool> UpdateOneAsync<TDocument>(TDocument modifiedDocument) where TDocument : IDocument
{
var updateRes = await HandlePartitioned(modifiedDocument).ReplaceOneAsync(x => x.Id == modifiedDocument.Id, modifiedDocument);
return updateRes.ModifiedCount == 1;
}
/// <summary>
/// Updates a document.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="modifiedDocument">The document with the modifications you want to persist.</param>
public bool UpdateOne<TDocument>(TDocument modifiedDocument) where TDocument : IDocument
{
var updateRes = HandlePartitioned(modifiedDocument).ReplaceOne(x => x.Id == modifiedDocument.Id, modifiedDocument);
return updateRes.ModifiedCount == 1;
}
#endregion Update
#region Delete
/// <summary>
/// Asynchronously deletes a document.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="TDocument">The document you want to delete.</param>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteOneAsync<TDocument>(TDocument document) where TDocument : IDocument
{
return (await HandlePartitioned(document).DeleteOneAsync(x => x.Id == document.Id)).DeletedCount;
}
/// <summary>
/// Deletes a document.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="TDocument">The document you want to delete.</param>
/// <returns>The number of documents deleted.</returns>
public long DeleteOne<TDocument>(TDocument document) where TDocument : IDocument
{
return HandlePartitioned(document).DeleteOne(x => x.Id == document.Id).DeletedCount;
}
/// <summary>
/// Deletes a document matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
public long DeleteOne<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).DeleteOne(filter).DeletedCount;
}
/// <summary>
/// Asynchronously deletes a document matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteOneAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return (await HandlePartitioned<TDocument>(partitionKey).DeleteOneAsync(filter)).DeletedCount;
}
/// <summary>
/// Asynchronously deletes the documents matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteManyAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return (await HandlePartitioned<TDocument>(partitionKey).DeleteManyAsync(filter)).DeletedCount;
}
/// <summary>
/// Asynchronously deletes a list of documents.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="documents">The list of documents to delete.</param>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteManyAsync<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument
{
if (!documents.Any())
{
return 0;
}
var idsTodelete = documents.Select(e => e.Id).ToArray();
return (await HandlePartitioned(documents.FirstOrDefault()).DeleteManyAsync(x => idsTodelete.Contains(x.Id))).DeletedCount;
}
/// <summary>
/// Deletes a list of documents.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="documents">The list of documents to delete.</param>
/// <returns>The number of documents deleted.</returns>
public long DeleteMany<TDocument>(IEnumerable<TDocument> documents) where TDocument : IDocument
{
if (!documents.Any())
{
return 0;
}
var idsTodelete = documents.Select(e => e.Id).ToArray();
return HandlePartitioned(documents.FirstOrDefault()).DeleteMany(x => idsTodelete.Contains(x.Id)).DeletedCount;
}
/// <summary>
/// Deletes the documents matching the condition of the LINQ expression filter.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>The number of documents deleted.</returns>
public long DeleteMany<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).DeleteMany(filter).DeletedCount;
}
#endregion Delete
#region Project
/// <summary>
/// Asynchronously returns a projected document matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <typeparam name="TProjection"></typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<TProjection> ProjectOneAsync<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class
{
return await HandlePartitioned<TDocument>(partitionKey).Find(filter)
.Project(projection)
.FirstOrDefaultAsync();
}
/// <summary>
/// Returns a projected document matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <typeparam name="TProjection"></typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
public TProjection ProjectOne<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter)
.Project(projection)
.FirstOrDefault();
}
/// <summary>
/// Asynchronously returns a list of projected documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <typeparam name="TProjection"></typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<List<TProjection>> ProjectManyAsync<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class
{
return await HandlePartitioned<TDocument>(partitionKey).Find(filter)
.Project(projection)
.ToListAsync();
}
/// <summary>
/// Asynchronously returns a list of projected documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <typeparam name="TProjection"></typeparam>
/// <param name="filter"></param>
/// <param name="projection">The projection expression.</param>
/// <param name="partitionKey">An optional partition key.</param>
public List<TProjection> ProjectMany<TDocument, TProjection>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TProjection>> projection, string partitionKey = null)
where TDocument : IDocument
where TProjection : class
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter)
.Project(projection)
.ToList();
}
#endregion
/// <summary>
/// Asynchronously returns a paginated list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter"></param>
/// <param name="skipNumber">The number of documents you want to skip. Default value is 0.</param>
/// <param name="takeNumber">The number of documents you want to take. Default value is 50.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<List<TDocument>> GetPaginatedAsync<TDocument>(Expression<Func<TDocument, bool>> filter, int skipNumber = 0, int takeNumber = 50, string partitionKey = null) where TDocument : IDocument
{
return await HandlePartitioned<TDocument>(partitionKey).Find(filter).Skip(skipNumber).Limit(takeNumber).ToListAsync();
}
#region Find And Update
/// <summary>
/// GetAndUpdateOne with filter
/// </summary>
/// <typeparam name="TDocument"></typeparam>
/// <param name="filter"></param>
/// <param name="update"></param>
/// <param name="options"></param>
/// <returns></returns>
public async Task<TDocument> GetAndUpdateOne<TDocument>(FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, FindOneAndUpdateOptions<TDocument, TDocument> options) where TDocument : IDocument
{
return await GetCollection<TDocument>().FindOneAndUpdateAsync(filter, update, options);
}
#endregion Find And Update
#region Private Methods
private IMongoCollection<TDocument> GetCollection<TDocument>(string partitionKey) where TDocument : IDocument
{
return _mongoDbContext.GetCollection<TDocument>(partitionKey);
}
private IMongoCollection<TDocument> GetCollection<TDocument>() where TDocument : IDocument
{
return _mongoDbContext.GetCollection<TDocument>();
}
private IMongoCollection<TDocument> HandlePartitioned<TDocument>(TDocument document) where TDocument : IDocument
{
if (document is IPartitionedDocument)
{
return GetCollection<TDocument>(((IPartitionedDocument)document).PartitionKey);
}
return GetCollection<TDocument>();
}
private IMongoCollection<TDocument> HandlePartitioned<TDocument>(string partitionKey) where TDocument : IDocument
{
if (!string.IsNullOrEmpty(partitionKey))
{
return GetCollection<TDocument>(partitionKey);
}
return GetCollection<TDocument>();
}
private void FormatDocument<TDocument>(TDocument document) where TDocument : IDocument
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
if (document.Id == default(Guid))
{
document.Id = Guid.NewGuid();
}
if (document.AddedAtUtc == default(DateTime))
{
document.AddedAtUtc = DateTime.UtcNow;
}
}
#endregion
}
}
@@ -1,35 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MongoDbGenericRepository")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MongoDbGenericRepository")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d154e7d0-9a3c-43ab-8e90-ed92bc4343f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,745 @@
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq.Expressions;
using MongoDbGenericRepository.Models;
using System.Linq;
namespace MongoDbGenericRepository
{
/// <summary>
/// The ReadOnlyMongoRepository implements the readonly functionality of the IReadOnlyMongoRepository.
/// </summary>
public class ReadOnlyMongoRepository : IReadOnlyMongoRepository
{
/// <summary>
/// The connection string.
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// The database name.
/// </summary>
public string DatabaseName { get; set; }
/// <summary>
/// The MongoDbContext
/// </summary>
protected IMongoDbContext MongoDbContext = null;
/// <summary>
/// The constructor taking a connection string and a database name.
/// </summary>
/// <param name="connectionString">The connection string of the MongoDb server.</param>
/// <param name="databaseName">The name of the database against which you want to perform operations.</param>
protected ReadOnlyMongoRepository(string connectionString, string databaseName)
{
MongoDbContext = new MongoDbContext(connectionString, databaseName);
}
/// <summary>
/// The contructor taking a <see cref="IMongoDbContext"/>.
/// </summary>
/// <param name="mongoDbContext">A mongodb context implementing <see cref="IMongoDbContext"/></param>
protected ReadOnlyMongoRepository(IMongoDbContext mongoDbContext)
{
MongoDbContext = mongoDbContext;
}
/// <summary>
/// The contructor taking a <see cref="IMongoDatabase"/>.
/// </summary>
/// <param name="mongoDatabase">A mongodb context implementing <see cref="IMongoDatabase"/></param>
protected ReadOnlyMongoRepository(IMongoDatabase mongoDatabase)
{
MongoDbContext = new MongoDbContext(mongoDatabase);
}
#region Read
/// <summary>
/// Asynchronously returns one document given its id.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<TDocument> GetByIdAsync<TDocument>(Guid id, string partitionKey = null) where TDocument : IDocument
{
var filter = Builders<TDocument>.Filter.Eq("Id", id);
return await HandlePartitioned<TDocument>(partitionKey).Find(filter).FirstOrDefaultAsync();
}
/// <summary>
/// Returns one document given its id.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
public TDocument GetById<TDocument>(Guid id, string partitionKey = null) where TDocument : IDocument
{
var filter = Builders<TDocument>.Filter.Eq("Id", id);
return HandlePartitioned<TDocument>(partitionKey).Find(filter).FirstOrDefault();
}
/// <summary>
/// Asynchronously returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<TDocument> GetOneAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return await HandlePartitioned<TDocument>(partitionKey).Find(filter).FirstOrDefaultAsync();
}
/// <summary>
/// Returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public TDocument GetOne<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter).FirstOrDefault();
}
/// <summary>
/// Returns a collection cursor.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public IFindFluent<TDocument, TDocument> GetCursor<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter);
}
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<bool> AnyAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
var count = await HandlePartitioned<TDocument>(partitionKey).CountDocumentsAsync(filter);
return (count > 0);
}
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public bool Any<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
var count = HandlePartitioned<TDocument>(partitionKey).CountDocuments(filter);
return (count > 0);
}
/// <summary>
/// Asynchronously returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<List<TDocument>> GetAllAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return await HandlePartitioned<TDocument>(partitionKey).Find(filter).ToListAsync();
}
/// <summary>
/// Returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public List<TDocument> GetAll<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter).ToList();
}
/// <summary>
/// Asynchronously counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partitionKey</param>
public async Task<long> CountAsync<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return await HandlePartitioned<TDocument>(partitionKey).CountDocumentsAsync(filter);
}
/// <summary>
/// Counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partitionKey</param>
public long Count<TDocument>(Expression<Func<TDocument, bool>> filter, string partitionKey = null) where TDocument : IDocument
{
return HandlePartitioned<TDocument>(partitionKey).Find(filter).CountDocuments();
}
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by descending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public async Task<TDocument> GetByMaxAsync<TDocument>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument
{
return await GetByMaxAsync<TDocument, Guid>(filter, maxValueSelector, partitionKey);
}
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by descending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
/// <returns></returns>
public TDocument GetByMax<TDocument>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument
{
return GetByMax<TDocument, Guid>(filter, maxValueSelector, partitionKey);
}
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public async Task<TDocument> GetByMinAsync<TDocument>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> minValueSelector, string partitionKey = null)
where TDocument : IDocument
{
return await GetByMinAsync<TDocument, Guid>(filter, minValueSelector, partitionKey);
}
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public TDocument GetByMin<TDocument>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> orderByAscending, string partitionKey = null)
where TDocument : IDocument
{
return GetByMin<TDocument, Guid>(filter, orderByAscending, partitionKey);
}
#endregion
#region Read TKey
/// <summary>
/// Asynchronously returns one document given its id.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<TDocument> GetByIdAsync<TDocument, TKey>(TKey id, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
var filter = Builders<TDocument>.Filter.Eq("Id", id);
return await HandlePartitioned<TDocument, TKey>(partitionKey).Find(filter).FirstOrDefaultAsync();
}
/// <summary>
/// Returns one document given its id.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="id">The Id of the document you want to get.</param>
/// <param name="partitionKey">An optional partition key.</param>
public TDocument GetById<TDocument, TKey>(TKey id, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
var filter = Builders<TDocument>.Filter.Eq("Id", id);
return HandlePartitioned<TDocument, TKey>(partitionKey).Find(filter).FirstOrDefault();
}
/// <summary>
/// Asynchronously returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<TDocument> GetOneAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return await HandlePartitioned<TDocument, TKey>(partitionKey).Find(filter).FirstOrDefaultAsync();
}
/// <summary>
/// Returns one document given an expression filter.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public TDocument GetOne<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return HandlePartitioned<TDocument, TKey>(partitionKey).Find(filter).FirstOrDefault();
}
/// <summary>
/// Returns a collection cursor.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public IFindFluent<TDocument, TDocument> GetCursor<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return HandlePartitioned<TDocument, TKey>(partitionKey).Find(filter);
}
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<bool> AnyAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
var count = await HandlePartitioned<TDocument, TKey>(partitionKey).CountDocumentsAsync(filter);
return (count > 0);
}
/// <summary>
/// Returns true if any of the document of the collection matches the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public bool Any<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
var count = HandlePartitioned<TDocument, TKey>(partitionKey).CountDocuments(filter);
return (count > 0);
}
/// <summary>
/// Asynchronously returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<List<TDocument>> GetAllAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return await HandlePartitioned<TDocument, TKey>(partitionKey).Find(filter).ToListAsync();
}
/// <summary>
/// Returns a list of the documents matching the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partition key.</param>
public List<TDocument> GetAll<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return HandlePartitioned<TDocument, TKey>(partitionKey).Find(filter).ToList();
}
/// <summary>
/// Asynchronously counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partitionKey</param>
public async Task<long> CountAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return await HandlePartitioned<TDocument, TKey>(partitionKey).CountDocumentsAsync(filter);
}
/// <summary>
/// Counts how many documents match the filter condition.
/// </summary>
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="partitionKey">An optional partitionKey</param>
public long Count<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return HandlePartitioned<TDocument, TKey>(partitionKey).Find(filter).CountDocuments();
}
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by descending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public async Task<TDocument> GetByMaxAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return await GetCollection<TDocument, TKey>(partitionKey).Find(Builders<TDocument>.Filter.Where(filter))
.SortByDescending(maxValueSelector)
.Limit(1)
.FirstOrDefaultAsync();
}
/// <summary>
/// Gets the document with the maximum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by descending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public TDocument GetByMax<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return GetCollection<TDocument, TKey>(partitionKey).Find(Builders<TDocument>.Filter.Where(filter))
.SortByDescending(maxValueSelector)
.Limit(1)
.FirstOrDefault();
}
/// <summary>
/// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public async Task<TDocument> GetByMinAsync<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> minValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return await GetCollection<TDocument, TKey>(partitionKey).Find(Builders<TDocument>.Filter.Where(filter))
.SortBy(minValueSelector)
.Limit(1)
.FirstOrDefaultAsync();
}
/// <summary>
/// Gets the document with the minimum value of a specified property in a MongoDB collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public TDocument GetByMin<TDocument, TKey>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, object>> minValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return GetCollection<TDocument, TKey>(partitionKey).Find(Builders<TDocument>.Filter.Where(filter))
.SortBy(minValueSelector)
.Limit(1)
.FirstOrDefault();
}
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partition key.</param>
private IFindFluent<TDocument, TDocument> GetMinMongoQuery<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> minValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return GetCollection<TDocument, TKey>(partitionKey).Find(Builders<TDocument>.Filter.Where(filter))
.SortBy(ConvertExpression(minValueSelector))
.Limit(1);
}
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by descending.</param>
/// <param name="partitionKey">An optional partition key.</param>
private IFindFluent<TDocument, TDocument> GetMaxMongoQuery<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return GetCollection<TDocument, TKey>(partitionKey).Find(Builders<TDocument>.Filter.Where(filter))
.SortByDescending(ConvertExpression(maxValueSelector))
.Limit(1);
}
/// <summary>
/// Gets the maximum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public async Task<TValue> GetMaxValueAsync<TDocument, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument
{
return await GetMaxValueAsync<TDocument, Guid, TValue>(filter, maxValueSelector, partitionKey);
}
/// <summary>
/// Gets the maximum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="orderByAscending">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public async Task<TValue> GetMaxValueAsync<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return await GetMaxMongoQuery<TDocument, TKey, TValue>(filter, maxValueSelector, partitionKey)
.Project(maxValueSelector)
.FirstOrDefaultAsync();
}
/// <summary>
/// Gets the maximum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public TValue GetMaxValue<TDocument, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument
{
return GetMaxValue<TDocument, Guid, TValue>(filter, maxValueSelector, partitionKey);
}
/// <summary>
/// Gets the maximum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="maxValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partitionKey.</param>
public TValue GetMaxValue<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> maxValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return GetMaxMongoQuery<TDocument, TKey, TValue>(filter, maxValueSelector, partitionKey)
.Project(maxValueSelector)
.FirstOrDefault();
}
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<TValue> GetMinValueAsync<TDocument, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> minValueSelector, string partitionKey = null)
where TDocument : IDocument
{
return await GetMinValueAsync<TDocument, Guid, TValue>(filter, minValueSelector, partitionKey);
}
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partition key.</param>
public async Task<TValue> GetMinValueAsync<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> minValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return await GetMinMongoQuery<TDocument, TKey, TValue>(filter, minValueSelector, partitionKey).Project(minValueSelector).FirstOrDefaultAsync();
}
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partition key.</param>
public TValue GetMinValue<TDocument, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> minValueSelector, string partitionKey = null)
where TDocument : IDocument
{
return GetMinValue<TDocument, Guid, TValue>(filter, minValueSelector, partitionKey);
}
/// <summary>
/// Gets the minimum value of a property in a mongodb collections that is satisfying the filter.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <typeparam name="TValue">The type of the value used to order the query.</typeparam>
/// <param name="filter">A LINQ expression filter.</param>
/// <param name="minValueSelector">A property selector to order by ascending.</param>
/// <param name="partitionKey">An optional partition key.</param>
public TValue GetMinValue<TDocument, TKey, TValue>(Expression<Func<TDocument, bool>> filter, Expression<Func<TDocument, TValue>> minValueSelector, string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return GetMinMongoQuery<TDocument, TKey, TValue>(filter, minValueSelector, partitionKey).Project(minValueSelector).FirstOrDefault();
}
#endregion
#region Utility Methods
/// <summary>
/// Gets a collections for the type TDocument with the matching partition key (if any).
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="partitionKey">An optional partition key.</param>
/// <returns>An <see cref="IMongoCollection{TDocument}"/></returns>
protected IMongoCollection<TDocument> GetCollection<TDocument>(string partitionKey = null) where TDocument : IDocument
{
return MongoDbContext.GetCollection<TDocument>(partitionKey);
}
/// <summary>
/// Gets a collections for the type TDocument
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="document">The document.</param>
/// <returns></returns>
protected IMongoCollection<TDocument> HandlePartitioned<TDocument>(TDocument document) where TDocument : IDocument
{
if (document is IPartitionedDocument)
{
return GetCollection<TDocument>(((IPartitionedDocument)document).PartitionKey);
}
return GetCollection<TDocument>();
}
/// <summary>
/// Gets a collections for a potentially partitioned document type.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="document">The document.</param>
/// <returns></returns>
protected IMongoCollection<TDocument> HandlePartitioned<TDocument, TKey>(TDocument document)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
if (document is IPartitionedDocument)
{
return GetCollection<TDocument, TKey>(((IPartitionedDocument)document).PartitionKey);
}
return GetCollection<TDocument, TKey>();
}
/// <summary>
/// Gets a collections for a potentially partitioned document type.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="partitionKey">The collection partition key.</param>
/// <returns></returns>
protected IMongoCollection<TDocument> HandlePartitioned<TDocument>(string partitionKey) where TDocument : IDocument
{
if (!string.IsNullOrEmpty(partitionKey))
{
return GetCollection<TDocument>(partitionKey);
}
return GetCollection<TDocument>();
}
/// <summary>
/// Gets a collections for the type TDocument with a partition key.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="partitionKey">The collection partition key.</param>
/// <returns></returns>
protected IMongoCollection<TDocument> GetCollection<TDocument, TKey>(string partitionKey = null)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
return MongoDbContext.GetCollection<TDocument>(partitionKey);
}
/// <summary>
/// Gets a collections for a potentially partitioned document type.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TKey">The type of the primary key.</typeparam>
/// <param name="partitionKey">The collection partition key.</param>
/// <returns></returns>
protected IMongoCollection<TDocument> HandlePartitioned<TDocument, TKey>(string partitionKey)
where TDocument : IDocument<TKey>
where TKey : IEquatable<TKey>
{
if (!string.IsNullOrEmpty(partitionKey))
{
return GetCollection<TDocument, TKey>(partitionKey);
}
return GetCollection<TDocument, TKey>();
}
/// <summary>
/// Converts a LINQ expression of TDocument, TValue to a LINQ expression of TDocument, object
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="expression">The expression to convert</param>
protected static Expression<Func<TDocument, object>> ConvertExpression<TDocument, TValue>(Expression<Func<TDocument, TValue>> expression)
{
var param = expression.Parameters[0];
Expression body = expression.Body;
var convert = Expression.Convert(body, typeof(object));
return Expression.Lambda<Func<TDocument, object>>(convert, param);
}
#endregion
}
}
@@ -0,0 +1,39 @@
using MongoDB.Bson;
using System;
namespace MongoDbGenericRepository.Utils
{
/// <summary>
/// The IdGenerator instance, used to generate Ids of different types.
/// </summary>
public static class IdGenerator
{
private static readonly Random Random = new Random();
/// <summary>
/// Generates a random value of a given type.
/// </summary>
/// <typeparam name="TKey">The type of the value to generate.</typeparam>
/// <returns>A value of type TKey.</returns>
public static TKey GetId<TKey>()
{
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.");
}
}
}
@@ -0,0 +1,428 @@
//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
{
/// <summary>
/// Container for registered Vocabularies. At present, only a single vocabulary is supported: Default.
/// </summary>
public static class Vocabularies
{
private static readonly Lazy<Vocabulary> Instance;
static Vocabularies()
{
Instance = new Lazy<Vocabulary>(BuildDefault, LazyThreadSafetyMode.PublicationOnly);
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
/// <summary>
/// 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.
/// </summary>
public class Vocabulary
{
internal Vocabulary()
{
}
private readonly List<Rule> _plurals = new List<Rule>();
private readonly List<Rule> _singulars = new List<Rule>();
private readonly List<string> _uncountables = new List<string>();
/// <summary>
/// Adds a word to the vocabulary which cannot easily be pluralized/singularized by RegEx, e.g. "person" and "people".
/// </summary>
/// <param name="singular">The singular form of the irregular word, e.g. "person".</param>
/// <param name="plural">The plural form of the irregular word, e.g. "people".</param>
/// <param name="matchEnding">True to match these words on their own as well as at the end of longer words. False, otherwise.</param>
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);
}
}
/// <summary>
/// Adds an uncountable word to the vocabulary, e.g. "fish". Will be ignored when plurality is changed.
/// </summary>
/// <param name="word">Word to be added to the list of uncountables.</param>
public void AddUncountable(string word)
{
_uncountables.Add(word.ToLower());
}
/// <summary>
/// Adds a rule to the vocabulary that does not follow trivial rules for pluralization, e.g. "bus" -> "buses"
/// </summary>
/// <param name="rule">RegEx to be matched, case insensitive, e.g. "(bus)es$"</param>
/// <param name="replacement">RegEx replacement e.g. "$1"</param>
public void AddPlural(string rule, string replacement)
{
_plurals.Add(new Rule(rule, replacement));
}
/// <summary>
/// Adds a rule to the vocabulary that does not follow trivial rules for singularization, e.g. "vertices/indices -> "vertex/index"
/// </summary>
/// <param name="rule">RegEx to be matched, case insensitive, e.g. ""(vert|ind)ices$""</param>
/// <param name="replacement">RegEx replacement e.g. "$1ex"</param>
public void AddSingular(string rule, string replacement)
{
_singulars.Add(new Rule(rule, replacement));
}
/// <summary>
/// Pluralizes the provided input considering irregular words
/// </summary>
/// <param name="word">Word to be pluralized</param>
/// <param name="inputIsKnownToBeSingular">Normally you call Pluralize on singular words; but if you're unsure call it with false</param>
/// <returns></returns>
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;
}
/// <summary>
/// Singularizes the provided input considering irregular words
/// </summary>
/// <param name="word">Word to be singularized</param>
/// <param name="inputIsKnownToBePlural">Normally you call Singularize on plural words; but if you're unsure call it with false</param>
/// <returns></returns>
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<Rule> 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);
}
}
}
/// <summary>
/// Inflector extensions
/// </summary>
public static class InflectorExtensions
{
/// <summary>
/// Pluralizes the provided input considering irregular words
/// </summary>
/// <param name="word">Word to be pluralized</param>
/// <param name="inputIsKnownToBeSingular">Normally you call Pluralize on singular words; but if you're unsure call it with false</param>
/// <returns></returns>
public static string Pluralize(this string word, bool inputIsKnownToBeSingular = true)
{
return Vocabularies.Default.Pluralize(word, inputIsKnownToBeSingular);
}
/// <summary>
/// Singularizes the provided input considering irregular words
/// </summary>
/// <param name="word">Word to be singularized</param>
/// <param name="inputIsKnownToBePlural">Normally you call Singularize on plural words; but if you're unsure call it with false</param>
/// <returns></returns>
public static string Singularize(this string word, bool inputIsKnownToBePlural = true)
{
return Vocabularies.Default.Singularize(word, inputIsKnownToBePlural);
}
/// <summary>
/// By default, pascalize converts strings to UpperCamelCase also removing underscores
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Pascalize(this string input)
{
return Regex.Replace(input, "(?:^|_)(.)", match => match.Groups[1].Value.ToUpper());
}
/// <summary>
/// Same as Pascalize except that the first character is lower case
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Camelize(this string input)
{
var word = Pascalize(input);
return word.Substring(0, 1).ToLower() + word.Substring(1);
}
/// <summary>
/// Separates the input words with underscore
/// </summary>
/// <param name="input">The string to be underscored</param>
/// <returns></returns>
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();
}
/// <summary>
/// Replaces underscores with dashes in the string
/// </summary>
/// <param name="underscoredWord"></param>
/// <returns></returns>
public static string Dasherize(this string underscoredWord)
{
return underscoredWord.Replace('_', '-');
}
/// <summary>
/// Replaces underscores with hyphens in the string
/// </summary>
/// <param name="underscoredWord"></param>
/// <returns></returns>
public static string Hyphenate(this string underscoredWord)
{
return Dasherize(underscoredWord);
}
}
}
@@ -0,0 +1,60 @@
using System;
namespace MongoDbGenericRepository.Utils
{
// Thanks BlueRaja - Danny Pflughoeft https://stackoverflow.com/a/13095144/5103354
/// <summary>
/// Extensions for the random number generator <see cref="Random"/>
/// </summary>
public static class RandomExtensions
{
/// <summary>
/// Returns a random long from min (inclusive) to max (exclusive)
/// </summary>
/// <param name="random">The given random instance</param>
/// <param name="min">The inclusive minimum bound</param>
/// <param name="max">The exclusive maximum bound. Must be greater than min</param>
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;
}
/// <summary>
/// Returns a random long from 0 (inclusive) to max (exclusive)
/// </summary>
/// <param name="random">The given random instance</param>
/// <param name="max">The exclusive maximum bound. Must be greater than 0</param>
public static long NextLong(this Random random, long max)
{
return random.NextLong(0, max);
}
/// <summary>
/// Returns a random long over all possible values of long (except long.MaxValue, similar to
/// random.Next())
/// </summary>
/// <param name="random">The given random instance</param>
public static long NextLong(this Random random)
{
return random.NextLong(long.MinValue, long.MaxValue);
}
}
}
-30
View File
@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
In the example below, the "SetAttributes" transform will change the value of
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an attribute "name" that has a value of "MyDB".
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
<system.web>
<!--
In the example below, the "Replace" transform will replace the entire
<customErrors> section of your web.config file.
Note that because there is only one customErrors section under the
<system.web> node, there is no need to use the "xdt:Locator" attribute.
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
-->
</system.web>
</configuration>
@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
In the example below, the "SetAttributes" transform will change the value of
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an attribute "name" that has a value of "MyDB".
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<!--
In the example below, the "Replace" transform will replace the entire
<customErrors> section of your web.config file.
Note that because there is only one customErrors section under the
<system.web> node, there is no need to use the "xdt:Locator" attribute.
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
-->
</system.web>
</configuration>
-32
View File
@@ -1,32 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Type="http://schemas.microsoft.com/packaging/2010/07/manifest" Target="/MongoDbGenericRepository.nuspec" Id="Rd7ba7aa97a7d4fb2" />
<Relationship Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="/package/services/metadata/core-properties/e5080d3094a649a39d247315f4dcd1ba.psmdcp" Id="Rcfffb2818c774b93" />
</Relationships>
@@ -1,3 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
</ApplicationInsights>
@@ -1,40 +0,0 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>Microsoft.CodeDom.Providers.DotNetCompilerPlatform</name>
</assembly>
<members>
<member name="T:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider">
<summary>
Provides access to instances of the .NET Compiler Platform C# code generator and code compiler.
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider.#ctor">
<summary>
Default Constructor
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider.CreateCompiler">
<summary>
Gets an instance of the .NET Compiler Platform C# code compiler.
</summary>
<returns>An instance of the .NET Compiler Platform C# code compiler</returns>
</member>
<member name="T:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider">
<summary>
Provides access to instances of the .NET Compiler Platform VB code generator and code compiler.
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider.#ctor">
<summary>
Default Constructor
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider.CreateCompiler">
<summary>
Gets an instance of the .NET Compiler Platform VB code compiler.
</summary>
<returns>An instance of the .NET Compiler Platform VB code compiler</returns>
</member>
</members>
</doc>
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More