Table of Contents

Class DB

Namespace
MongoDB.Entities
Assembly
MongoDB.Entities.dll

The main entrypoint for all data access methods of the library

public class DB
Inheritance
DB
Derived
Inherited Members

Constructors

DB(DB)

protected DB(DB source)

Parameters

source DB

Properties

Default

Gets the default DB instance when previously initialized.

public static DB Default { get; }

Property Value

DB

Exceptions

InvalidOperationException

Thrown when no databases have been initialized.

IgnoreGlobalFilters

setting this to true will cause any global filters to be ignored when actions are performed with this DB instance.

public bool IgnoreGlobalFilters { get; set; }

Property Value

bool

ModifiedBy

The value of this property will be automatically set on entities when saving/updating if the entity has a ModifiedBy property

public ModifiedBy? ModifiedBy { get; }

Property Value

ModifiedBy

SessionHandle

protected IClientSessionHandle? SessionHandle { get; set; }

Property Value

IClientSessionHandle

Methods

AllDatabaseNamesAsync(MongoClientSettings)

Gets a list of all database names from the server

public static Task<IEnumerable<string>> AllDatabaseNamesAsync(MongoClientSettings settings)

Parameters

settings MongoClientSettings

A MongoClientSettings object

Returns

Task<IEnumerable<string>>

AllDatabaseNamesAsync(string, int)

Gets a list of all database names from the server

public static Task<IEnumerable<string>> AllDatabaseNamesAsync(string host = "127.0.0.1", int port = 27017)

Parameters

host string

Address of the MongoDB server

port int

Port number of the server

Returns

Task<IEnumerable<string>>

ChangeDefaultDatabase(string, MongoClientSettings?)

Switches the default database at runtime

WARNING: Use at your own risk!!! Might result in entities getting saved in the wrong databases under high concurrency situations.

TIP: Make sure to cancel any watchers (change-streams) before switching the default database.

public static void ChangeDefaultDatabase(string name, MongoClientSettings? settings = null)

Parameters

name string

The name of the database to mark as the new default database

settings MongoClientSettings

The MongoClient we want to get the database from

CollectionName<T>()

Gets the collection name for a given entity type

public string CollectionName<T>() where T : IEntity

Returns

string

Type Parameters

T

The type of entity to get the collection name for

Collection<T>()

Gets the IMongoCollection for a given IEntity type.

TIP: Try never to use this unless really necessary.

public IMongoCollection<T> Collection<T>() where T : IEntity

Returns

IMongoCollection<T>

Type Parameters

T

Any class that implements IEntity

CountAsync<T>(FilterDefinition<T>, CancellationToken, CountOptions?, bool)

Gets an accurate count of how many total entities are in the collection for a given entity type

public Task<long> CountAsync<T>(FilterDefinition<T> filter, CancellationToken cancellation = default, CountOptions? options = null, bool ignoreGlobalFilters = false) where T : IEntity

Parameters

filter FilterDefinition<T>

A filter definition

cancellation CancellationToken

An optional cancellation token

options CountOptions

An optional CountOptions object

ignoreGlobalFilters bool

Set to true if you'd like to ignore any global filters for this operation

Returns

Task<long>

Type Parameters

T

The entity type to get the count for

CountAsync<T>(Func<FilterDefinitionBuilder<T>, FilterDefinition<T>>, CancellationToken, CountOptions?, bool)

Gets an accurate count of how many total entities are in the collection for a given entity type

public Task<long> CountAsync<T>(Func<FilterDefinitionBuilder<T>, FilterDefinition<T>> filter, CancellationToken cancellation = default, CountOptions? options = null, bool ignoreGlobalFilters = false) where T : IEntity

Parameters

filter Func<FilterDefinitionBuilder<T>, FilterDefinition<T>>

f => f.Eq(x => x.Prop, Value) & f.Gt(x => x.Prop, Value)

cancellation CancellationToken

An optional cancellation token

options CountOptions

An optional CountOptions object

ignoreGlobalFilters bool

Set to true if you'd like to ignore any global filters for this operation

Returns

Task<long>

Type Parameters

T

The entity type to get the count for

CountAsync<T>(Expression<Func<T, bool>>, CancellationToken, CountOptions?, bool)

Gets an accurate count of how many entities are matched for a given expression/filter

public Task<long> CountAsync<T>(Expression<Func<T, bool>> expression, CancellationToken cancellation = default, CountOptions? options = null, bool ignoreGlobalFilters = false) where T : IEntity

Parameters

expression Expression<Func<T, bool>>

A lambda expression for getting the count for a subset of the data

cancellation CancellationToken

An optional cancellation token

options CountOptions

An optional CountOptions object

ignoreGlobalFilters bool

Set to true if you'd like to ignore any global filters for this operation

Returns

Task<long>

Type Parameters

T

The entity type to get the count for

CountAsync<T>(CancellationToken)

Gets an accurate count of how many total entities are in the collection for a given entity type

public Task<long> CountAsync<T>(CancellationToken cancellation = default) where T : IEntity

Parameters

cancellation CancellationToken

An optional cancellation token

Returns

Task<long>

Type Parameters

T

The entity type to get the count for

CountEstimatedAsync<T>(CancellationToken)

Gets a fast estimation of how many documents are in the collection using metadata.

HINT: The estimation may not be exactly accurate.

public Task<long> CountEstimatedAsync<T>(CancellationToken cancellation = default) where T : IEntity

Parameters

cancellation CancellationToken

An optional cancellation token

Returns

Task<long>

Type Parameters

T

The entity type to get the count for

CreateCollectionAsync<T>(Action<CreateCollectionOptions<T>>, CancellationToken, IClientSessionHandle?)

Creates a collection for an Entity type explicitly using the given options

public Task CreateCollectionAsync<T>(Action<CreateCollectionOptions<T>> options, CancellationToken cancellation = default, IClientSessionHandle? session = null) where T : IEntity

Parameters

options Action<CreateCollectionOptions<T>>

The options to use for collection creation

cancellation CancellationToken

An optional cancellation token

session IClientSessionHandle

An optional session if using within a transaction

Returns

Task

Type Parameters

T

The type of entity that will be stored in the created collection

Database()

Gets the IMongoDatabase for a given database name if it has been previously initialized. You can also get the default database by passing 'default' or 'null' for the name parameter.

public IMongoDatabase Database()

Returns

IMongoDatabase

DatabaseName()

Gets the name of the database which this DB instance is attached to.

public string DatabaseName()

Returns

string

DeleteAsync<T>(FilterDefinition<T>, CancellationToken, Collation?)

Deletes matching entities with a filter definition

HINT: If the expression matches more than 100,000 entities, they will be deleted in batches of 100k.

HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.

public Task<DeleteResult> DeleteAsync<T>(FilterDefinition<T> filter, CancellationToken cancellation = default, Collation? collation = null) where T : IEntity

Parameters

filter FilterDefinition<T>

A filter definition for matching entities to delete.

cancellation CancellationToken

An optional cancellation token

collation Collation

An optional collation object

Returns

Task<DeleteResult>

Type Parameters

T

Any class that implements IEntity

DeleteAsync<T>(IEnumerable<object?>, CancellationToken)

Deletes entities using a collection of IDs

HINT: If more than 100,000 IDs are passed in, they will be processed in batches of 100k.

HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.

public Task<DeleteResult> DeleteAsync<T>(IEnumerable<object?> IDs, CancellationToken cancellation = default) where T : IEntity

Parameters

IDs IEnumerable<object>

An IEnumerable of entity IDs

cancellation CancellationToken

An optional cancellation token

Returns

Task<DeleteResult>

Type Parameters

T

Any class that implements IEntity

DeleteAsync<T>(IEnumerable<T>, CancellationToken)

Deletes entities using a collection of IDs

HINT: If more than 100,000 IDs are passed in, they will be processed in batches of 100k.

HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.

public Task<DeleteResult> DeleteAsync<T>(IEnumerable<T> entities, CancellationToken cancellation = default) where T : IEntity

Parameters

entities IEnumerable<T>

An IEnumerable of entities

cancellation CancellationToken

An optional cancellation token

Returns

Task<DeleteResult>

Type Parameters

T

Any class that implements IEntity

DeleteAsync<T>(Func<FilterDefinitionBuilder<T>, FilterDefinition<T>>, CancellationToken, Collation?)

Deletes matching entities with a filter expression

HINT: If the expression matches more than 100,000 entities, they will be deleted in batches of 100k.

HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.

public Task<DeleteResult> DeleteAsync<T>(Func<FilterDefinitionBuilder<T>, FilterDefinition<T>> filter, CancellationToken cancellation = default, Collation? collation = null) where T : IEntity

Parameters

filter Func<FilterDefinitionBuilder<T>, FilterDefinition<T>>

f => f.Eq(x => x.Prop, Value) & f.Gt(x => x.Prop, Value)

cancellation CancellationToken

An optional cancellation token

collation Collation

An optional collation object

Returns

Task<DeleteResult>

Type Parameters

T

Any class that implements IEntity

DeleteAsync<T>(Expression<Func<T, bool>>, CancellationToken, Collation?)

Deletes matching entities with an expression

HINT: If the expression matches more than 100,000 entities, they will be deleted in batches of 100k.

HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.

public Task<DeleteResult> DeleteAsync<T>(Expression<Func<T, bool>> expression, CancellationToken cancellation = default, Collation? collation = null) where T : IEntity

Parameters

expression Expression<Func<T, bool>>

A lambda expression for matching entities to delete.

cancellation CancellationToken

An optional cancellation token

collation Collation

An optional collation object

Returns

Task<DeleteResult>

Type Parameters

T

Any class that implements IEntity

DeleteAsync<T>(object, CancellationToken)

Deletes a single entity from MongoDB.

HINT: If this entity is referenced by one-to-many/many-to-many relationships, those references are also deleted.

public Task<DeleteResult> DeleteAsync<T>(object ID, CancellationToken cancellation = default) where T : IEntity

Parameters

ID object

The Id of the entity to delete

cancellation CancellationToken

An optional cancellation token

Returns

Task<DeleteResult>

Type Parameters

T

Any class that implements IEntity

DeleteAsync<T>(T, CancellationToken)

Deletes a single entity from MongoDB.

HINT: If this entity is referenced by one-to-many/many-to-many relationships, those references are also deleted.

public Task<DeleteResult> DeleteAsync<T>(T entity, CancellationToken cancellation = default) where T : IEntity

Parameters

entity T

The entity to delete

cancellation CancellationToken

An optional cancellation token

Returns

Task<DeleteResult>

Type Parameters

T

Any class that implements IEntity

Distinct<T, TProperty>()

Represents a MongoDB Distinct command where you can get back distinct values for a given property of a given Entity.

public Distinct<T, TProperty> Distinct<T, TProperty>() where T : IEntity

Returns

Distinct<T, TProperty>

Type Parameters

T

Any Entity that implements IEntity interface

TProperty

The type of the property of the entity you'd like to get unique values for

DropCollectionAsync<T>(IClientSessionHandle?)

Deletes the collection of a given entity type as well as the join collections for that entity.

TIP: When deleting a collection, all relationships associated with that entity type is also deleted.

public Task DropCollectionAsync<T>(IClientSessionHandle? session = null) where T : IEntity

Parameters

session IClientSessionHandle

An optional session if using within a transaction

Returns

Task

Type Parameters

T

The entity type to drop the collection of

Entity<T>()

Returns a new instance of the supplied IEntity type

public static T Entity<T>() where T : IEntity, new()

Returns

T

Type Parameters

T

Any class that implements IEntity

Entity<T>(object)

Returns a new instance of the supplied IEntity type with the ID set to the supplied value

public static T Entity<T>(object ID) where T : IEntity, new()

Parameters

ID object

The ID to set on the returned instance

Returns

T

Type Parameters

T

Any class that implements IEntity

File<T>(string)

Returns a DataStreamer object to enable uploading/downloading file data directly by supplying the ID of the file entity

public DataStreamer<T> File<T>(string ID) where T : FileEntity<T>, new()

Parameters

ID string

The ID of the file entity

Returns

DataStreamer<T>

Type Parameters

T

The file entity type

Filter<T>()

Exposes the mongodb Filter Definition Builder for a given type.

public static FilterDefinitionBuilder<T> Filter<T>() where T : IEntity

Returns

FilterDefinitionBuilder<T>

Type Parameters

T

Any class that implements IEntity

Find<T>()

Represents a MongoDB Find command

TIP: Specify your criteria using .Match() .Sort() .Skip() .Take() .Project() .Option() methods and finally call .Execute()

public Find<T> Find<T>() where T : IEntity

Returns

Find<T>

Type Parameters

T

Any class that implements IEntity

Find<T, TProjection>()

Represents a MongoDB Find command

TIP: Specify your criteria using .Match() .Sort() .Skip() .Take() .Project() .Option() methods and finally call .Execute()

public Find<T, TProjection> Find<T, TProjection>() where T : IEntity

Returns

Find<T, TProjection>

Type Parameters

T

Any class that implements IEntity

TProjection

The type that is returned by projection

FluentTextSearch<T>(Search, string, bool, bool, string?, AggregateOptions?)

Start a fluent aggregation pipeline with a $text stage with the supplied parameters

TIP: Make sure to define a text index with DB.Index<T>() before searching

public IAggregateFluent<T> FluentTextSearch<T>(Search searchType, string searchTerm, bool caseSensitive = false, bool diacriticSensitive = false, string? language = null, AggregateOptions? options = null) where T : IEntity

Parameters

searchType Search

The type of text matching to do

searchTerm string

The search term

caseSensitive bool

Case sensitivity of the search (optional)

diacriticSensitive bool

Diacritic sensitivity of the search (optional)

language string

The language for the search (optional)

options AggregateOptions

Options for finding documents (not required)

Returns

IAggregateFluent<T>

Type Parameters

T

Fluent<T>(AggregateOptions?)

Exposes the MongoDB collection for the given entity type as IAggregateFluent in order to facilitate Fluent queries

public IAggregateFluent<T> Fluent<T>(AggregateOptions? options = null) where T : IEntity

Parameters

options AggregateOptions

The options for the aggregation. This is not required.

Returns

IAggregateFluent<T>

Type Parameters

T

The type of entity

GeoNear<T>(Coordinates2D, Expression<Func<T, object?>>, bool, int?, int?, int?, BsonDocument?, int?, Expression<Func<T, object?>>?, string?, AggregateOptions?)

Start a fluent aggregation pipeline with a $GeoNear stage with the supplied parameters

public IAggregateFluent<T> GeoNear<T>(Coordinates2D NearCoordinates, Expression<Func<T, object?>> DistanceField, bool Spherical = true, int? MaxDistance = null, int? MinDistance = null, int? Limit = null, BsonDocument? Query = null, int? DistanceMultiplier = null, Expression<Func<T, object?>>? IncludeLocations = null, string? IndexKey = null, AggregateOptions? options = null) where T : IEntity

Parameters

NearCoordinates Coordinates2D

The coordinates from which to find documents from

DistanceField Expression<Func<T, object>>

x => x.Distance

Spherical bool

Calculate distances using spherical geometry or not

MaxDistance int?

The maximum distance in meters from the center point that the documents can be

MinDistance int?

The minimum distance in meters from the center point that the documents can be

Limit int?

The maximum number of documents to return

Query BsonDocument

Limits the results to the documents that match the query

DistanceMultiplier int?

The factor to multiply all distances returned by the query

IncludeLocations Expression<Func<T, object>>

Specify the output field to store the point used to calculate the distance

IndexKey string
options AggregateOptions

The options for the aggregation. This is not required.

Returns

IAggregateFluent<T>

Type Parameters

T

The type of entity

Index<T>()

Represents an index for a given IEntity

TIP: Define the keys first with .Key() method and finally call the .InitAsync() method.

public Index<T> Index<T>() where T : IEntity

Returns

Index<T>

Type Parameters

T

Any class that implements IEntity

InitAsync(string, MongoClientSettings?, MongoDatabaseSettings?, bool)

Returns the cached DB instance or creates and initializes a new DB instance with the given connection parameters.

WARNING: will throw an error if server is not reachable!

You can call this method as many times as you want (such as in serverless functions) with the same parameters and the connections won't get duplicated.
public static Task<DB> InitAsync(string dbName, MongoClientSettings? clientSettings = null, MongoDatabaseSettings? databaseSettings = null, bool skipNetworkPing = false)

Parameters

dbName string

Name of the database

clientSettings MongoClientSettings

A MongoClientSettings object

databaseSettings MongoDatabaseSettings

The database settings to create the database with

skipNetworkPing bool

Should we ping the database

Returns

Task<DB>

DB instance

InsertAsync<T>(IEnumerable<T>, CancellationToken)

Inserts a batch of new entities into the collection.

public Task<BulkWriteResult<T>> InsertAsync<T>(IEnumerable<T> entities, CancellationToken cancellation = default) where T : IEntity

Parameters

entities IEnumerable<T>

The entities to persist

cancellation CancellationToken

And optional cancellation token

Returns

Task<BulkWriteResult<T>>

Type Parameters

T

Any class that implements IEntity

InsertAsync<T>(T, CancellationToken)

Inserts a new entity into the collection.

public Task InsertAsync<T>(T entity, CancellationToken cancellation = default) where T : IEntity

Parameters

entity T

The instance to persist

cancellation CancellationToken

And optional cancellation token

Returns

Task

Type Parameters

T

Any class that implements IEntity

Instance(string?, MongoClientSettings?)

Gets the DB instance for a given database name if it has been previously initialized.

public static DB Instance(string? dbName = null, MongoClientSettings? settings = null)

Parameters

dbName string

The name of the database to retrieve

settings MongoClientSettings

The host we want the instance from

Returns

DB

MigrateAsync()

Executes migration classes that implement the IMigration interface in the correct order to transform the database.

TIP: Write classes with names such as: _001_rename_a_field.cs, _002_delete_a_field.cs, etc. and implement IMigration interface on them. Call this method at the startup of the application in order to run the migrations.

public Task MigrateAsync()

Returns

Task

MigrateAsync<T>()

Discover and run migrations from the same assembly as the specified type.

public Task MigrateAsync<T>() where T : class

Returns

Task

Type Parameters

T

A type that is from the same assembly as the migrations you want to run

MigrationsAsync(IEnumerable<IMigration>)

Executes the given collection of IMigrations in the correct order to transform the database.

public Task MigrationsAsync(IEnumerable<IMigration> migrations)

Parameters

migrations IEnumerable<IMigration>

The collection of migrations to execute

Returns

Task

NextSequentialNumberAsync(string, CancellationToken)

Returns an atomically generated sequential number for the given sequence name everytime the method is called

public Task<ulong> NextSequentialNumberAsync(string sequenceName, CancellationToken cancellation = default)

Parameters

sequenceName string

The name of the sequence to get the next number for

cancellation CancellationToken

An optional cancellation token

Returns

Task<ulong>

NextSequentialNumberAsync<T>(CancellationToken)

Returns an atomically generated sequential number for the given Entity type everytime the method is called

public Task<ulong> NextSequentialNumberAsync<T>(CancellationToken cancellation = default) where T : IEntity

Parameters

cancellation CancellationToken

An optional cancellation token

Returns

Task<ulong>

Type Parameters

T

The type of entity to get the next sequential number for

OnBeforeSave<T>()

This event hook will be triggered right before an entity is persisted

protected virtual Action<T>? OnBeforeSave<T>() where T : IEntity

Returns

Action<T>

Type Parameters

T

Any entity that implements IEntity

OnBeforeUpdate<T>()

This event hook will be triggered right before an update/replace command is executed

protected virtual Action<UpdateBase<T>>? OnBeforeUpdate<T>() where T : IEntity

Returns

Action<UpdateBase<T>>

Type Parameters

T

Any entity that implements IEntity

PagedSearch<T>()

Represents an aggregation query that retrieves results with easy paging support.

public PagedSearch<T> PagedSearch<T>() where T : IEntity

Returns

PagedSearch<T>

Type Parameters

T

Any class that implements IEntity

PagedSearch<T, TProjection>()

Represents an aggregation query that retrieves results with easy paging support.

public PagedSearch<T, TProjection> PagedSearch<T, TProjection>() where T : IEntity

Returns

PagedSearch<T, TProjection>

Type Parameters

T

Any class that implements IEntity

TProjection

The type you'd like to project the results to.

PipelineAsync<T, TResult>(Template<T, TResult>, CancellationToken, AggregateOptions?)

Executes an aggregation pipeline by supplying a 'Template' object and get a list of results

public Task<List<TResult>> PipelineAsync<T, TResult>(Template<T, TResult> template, CancellationToken cancellation = default, AggregateOptions? options = null) where T : IEntity

Parameters

template Template<T, TResult>

A 'Template' object with tags replaced

cancellation CancellationToken

An optional cancellation token

options AggregateOptions

The options for the aggregation. This is not required.

Returns

Task<List<TResult>>

Type Parameters

T

Any class that implements IEntity

TResult

The type of the resulting objects

PipelineCursorAsync<T, TResult>(Template<T, TResult>, CancellationToken, AggregateOptions?)

Executes an aggregation pipeline by supplying a 'Template' object and returns a cursor

public Task<IAsyncCursor<TResult>> PipelineCursorAsync<T, TResult>(Template<T, TResult> template, CancellationToken cancellation = default, AggregateOptions? options = null) where T : IEntity

Parameters

template Template<T, TResult>

A 'Template' object with tags replaced

cancellation CancellationToken

An optional cancellation token

options AggregateOptions

The options for the aggregation. This is not required.

Returns

Task<IAsyncCursor<TResult>>

Type Parameters

T

Any class that implements IEntity

TResult

The type of the resulting objects

PipelineFirstAsync<T, TResult>(Template<T, TResult>, CancellationToken, AggregateOptions?)

Executes an aggregation pipeline by supplying a 'Template' object and get the first result or default value if not found.

public Task<TResult> PipelineFirstAsync<T, TResult>(Template<T, TResult> template, CancellationToken cancellation = default, AggregateOptions? options = null) where T : IEntity

Parameters

template Template<T, TResult>

A 'Template' object with tags replaced

cancellation CancellationToken

An optional cancellation token

options AggregateOptions

The options for the aggregation. This is not required.

Returns

Task<TResult>

Type Parameters

T

Any class that implements IEntity

TResult

The type of the resulting object

PipelineSingleAsync<T, TResult>(Template<T, TResult>, CancellationToken, AggregateOptions?)

Executes an aggregation pipeline by supplying a 'Template' object and get a single result or default value if not found. If more than one entity is found, it will throw an exception.

public Task<TResult> PipelineSingleAsync<T, TResult>(Template<T, TResult> template, CancellationToken cancellation = default, AggregateOptions? options = null) where T : IEntity

Parameters

template Template<T, TResult>

A 'Template' object with tags replaced

cancellation CancellationToken

An optional cancellation token

options AggregateOptions

The options for the aggregation. This is not required.

Returns

Task<TResult>

Type Parameters

T

Any class that implements IEntity

TResult

The type of the resulting object

Projection<T>()

Exposes the mongodb Projection Definition Builder for a given type.

public static ProjectionDefinitionBuilder<T> Projection<T>() where T : IEntity

Returns

ProjectionDefinitionBuilder<T>

Type Parameters

T

Any class that implements IEntity

Queryable<T>(AggregateOptions?)

Exposes the MongoDB collection for the given entity type as IQueryable in order to facilitate LINQ queries

public IQueryable<T> Queryable<T>(AggregateOptions? options = null) where T : IEntity

Parameters

options AggregateOptions

The aggregate options

Returns

IQueryable<T>

Type Parameters

T

The type of entity

Replace<T>()

Represents a ReplaceOne command, which can replace the first matched document with a given entity

TIP: Specify a filter first with the .Match(). Then set entity with .WithEntity() and finally call .Execute() to run the command.

public Replace<T> Replace<T>() where T : IEntity

Returns

Replace<T>

Type Parameters

T

Any class that implements IEntity

SaveAsync<T>(IEnumerable<T>, CancellationToken)

Saves a batch of complete entities replacing existing ones or creating new ones if they do not exist. If ID value is null, a new entity is created. If ID has a value, then existing entity is replaced.

public Task<BulkWriteResult<T>> SaveAsync<T>(IEnumerable<T> entities, CancellationToken cancellation = default) where T : IEntity

Parameters

entities IEnumerable<T>

The entities to persist

cancellation CancellationToken

And optional cancellation token

Returns

Task<BulkWriteResult<T>>

Type Parameters

T

Any class that implements IEntity

SaveAsync<T>(T, CancellationToken)

Saves a complete entity replacing an existing entity or creating a new one if it does not exist. If ID value is null, a new entity is created. If ID has a value, then existing entity is replaced.

public Task SaveAsync<T>(T entity, CancellationToken cancellation = default) where T : IEntity

Parameters

entity T

The instance to persist

cancellation CancellationToken

And optional cancellation token

Returns

Task

Type Parameters

T

Any class that implements IEntity

SaveExceptAsync<T>(IEnumerable<T>, IEnumerable<string>, CancellationToken)

Saves a batch of entities partially excluding the specified subset of properties. If ID value is null, a new entity is created. If ID has a value, then existing entity is updated.

TIP: The properties to be saved can be specified with an IEnumerable. Property names must match exactly.

public Task<BulkWriteResult<T>> SaveExceptAsync<T>(IEnumerable<T> entities, IEnumerable<string> propNames, CancellationToken cancellation = default) where T : IEntity

Parameters

entities IEnumerable<T>

The batch of entities to save

propNames IEnumerable<string>

new List { "PropOne", "PropTwo" }

cancellation CancellationToken

An optional cancellation token

Returns

Task<BulkWriteResult<T>>

Type Parameters

T

Any class that implements IEntity

SaveExceptAsync<T>(IEnumerable<T>, Expression<Func<T, object?>>, CancellationToken)

Saves a batch of entities partially excluding the specified subset of properties. If ID value is null, a new entity is created. If ID has a value, then existing entity is updated.

TIP: The properties to be excluded can be specified with a 'New' expression. You can only specify root level properties with the expression.

public Task<BulkWriteResult<T>> SaveExceptAsync<T>(IEnumerable<T> entities, Expression<Func<T, object?>> members, CancellationToken cancellation = default) where T : IEntity

Parameters

entities IEnumerable<T>

The batch of entities to save

members Expression<Func<T, object>>

x => new { x.PropOne, x.PropTwo }

cancellation CancellationToken

An optional cancellation token

Returns

Task<BulkWriteResult<T>>

Type Parameters

T

Any class that implements IEntity

SaveExceptAsync<T>(T, IEnumerable<string>, CancellationToken)

Saves an entity partially excluding the specified subset of properties. If ID value is null, a new entity is created. If ID has a value, then existing entity is updated.

TIP: The properties to be saved can be specified with an IEnumerable. Property names must match exactly.

public Task<UpdateResult> SaveExceptAsync<T>(T entity, IEnumerable<string> propNames, CancellationToken cancellation = default) where T : IEntity

Parameters

entity T

The entity to save

propNames IEnumerable<string>

new List { "PropOne", "PropTwo" }

cancellation CancellationToken

An optional cancellation token

Returns

Task<UpdateResult>

Type Parameters

T

Any class that implements IEntity

SaveExceptAsync<T>(T, Expression<Func<T, object?>>, CancellationToken)

Saves an entity partially excluding the specified subset of properties. If ID value is null, a new entity is created. If ID has a value, then existing entity is updated.

TIP: The properties to be excluded can be specified with a 'New' expression. You can only specify root level properties with the expression.

public Task<UpdateResult> SaveExceptAsync<T>(T entity, Expression<Func<T, object?>> members, CancellationToken cancellation = default) where T : IEntity

Parameters

entity T

The entity to save

members Expression<Func<T, object>>

x => new { x.PropOne, x.PropTwo }

cancellation CancellationToken

An optional cancellation token

Returns

Task<UpdateResult>

Type Parameters

T

Any class that implements IEntity

SaveOnlyAsync<T>(IEnumerable<T>, IEnumerable<string>, CancellationToken)

Saves a batch of entities partially with only the specified subset of properties. If ID value is null, a new entity is created. If ID has a value, then existing entity is updated.

TIP: The properties to be saved can be specified with an IEnumerable. Property names must match exactly.

public Task<BulkWriteResult<T>> SaveOnlyAsync<T>(IEnumerable<T> entities, IEnumerable<string> propNames, CancellationToken cancellation = default) where T : IEntity

Parameters

entities IEnumerable<T>

The batch of entities to save

propNames IEnumerable<string>

new List { "PropOne", "PropTwo" }

cancellation CancellationToken

An optional cancellation token

Returns

Task<BulkWriteResult<T>>

Type Parameters

T

Any class that implements IEntity

SaveOnlyAsync<T>(IEnumerable<T>, Expression<Func<T, object?>>, CancellationToken)

Saves a batch of entities partially with only the specified subset of properties. If ID value is null, a new entity is created. If ID has a value, then existing entity is updated.

TIP: The properties to be saved can be specified with a 'New' expression. You can only specify root level properties with the expression.

public Task<BulkWriteResult<T>> SaveOnlyAsync<T>(IEnumerable<T> entities, Expression<Func<T, object?>> members, CancellationToken cancellation = default) where T : IEntity

Parameters

entities IEnumerable<T>

The batch of entities to save

members Expression<Func<T, object>>

x => new { x.PropOne, x.PropTwo }

cancellation CancellationToken

An optional cancellation token

Returns

Task<BulkWriteResult<T>>

Type Parameters

T

Any class that implements IEntity

SaveOnlyAsync<T>(T, IEnumerable<string>, CancellationToken)

Saves an entity partially with only the specified subset of properties. If ID value is null, a new entity is created. If ID has a value, then existing entity is updated.

TIP: The properties to be saved can be specified with an IEnumerable. Property names must match exactly.

public Task<UpdateResult> SaveOnlyAsync<T>(T entity, IEnumerable<string> propNames, CancellationToken cancellation = default) where T : IEntity

Parameters

entity T

The entity to save

propNames IEnumerable<string>

new List { "PropOne", "PropTwo" }

cancellation CancellationToken

An optional cancellation token

Returns

Task<UpdateResult>

Type Parameters

T

Any class that implements IEntity

SaveOnlyAsync<T>(T, Expression<Func<T, object?>>, CancellationToken)

Saves an entity partially with only the specified subset of properties. If ID value is null, a new entity is created. If ID has a value, then existing entity is updated.

TIP: The properties to be saved can be specified with a 'New' expression. You can only specify root level properties with the expression.

public Task<UpdateResult> SaveOnlyAsync<T>(T entity, Expression<Func<T, object?>> members, CancellationToken cancellation = default) where T : IEntity

Parameters

entity T

The entity to save

members Expression<Func<T, object>>

x => new { x.PropOne, x.PropTwo }

cancellation CancellationToken

An optional cancellation token

Returns

Task<UpdateResult>

Type Parameters

T

Any class that implements IEntity

SavePreservingAsync<T>(T, CancellationToken)

Saves an entity partially while excluding some properties. The properties to be excluded can be specified using the [Preserve] or [DontPreserve] attributes.

public Task<UpdateResult> SavePreservingAsync<T>(T entity, CancellationToken cancellation = default) where T : IEntity

Parameters

entity T

The entity to save

cancellation CancellationToken

An optional cancellation token

Returns

Task<UpdateResult>

Type Parameters

T

Any class that implements IEntity

SetGlobalFilter(Type, string, bool)

Specify a global filter to be applied to all operations performed with this DBContext

protected void SetGlobalFilter(Type type, string jsonString, bool prepend = false)

Parameters

type Type

The type of Entity this global filter should be applied to

jsonString string

A JSON string filter definition to be applied

prepend bool

Set to true if you want to prepend this global filter to your operation filters instead of being appended

SetGlobalFilterForBaseClass<TBase>(FilterDefinition<TBase>, bool)

Specify a global filter to be applied to all operations performed with this DBContext

protected void SetGlobalFilterForBaseClass<TBase>(FilterDefinition<TBase> filter, bool prepend = false) where TBase : IEntity

Parameters

filter FilterDefinition<TBase>

A filter definition to be applied

prepend bool

Set to true if you want to prepend this global filter to your operation filters instead of being appended

Type Parameters

TBase

The type of the base class

SetGlobalFilterForBaseClass<TBase>(Func<FilterDefinitionBuilder<TBase>, FilterDefinition<TBase>>, bool)

Specify a global filter to be applied to all operations performed with this DBContext

protected void SetGlobalFilterForBaseClass<TBase>(Func<FilterDefinitionBuilder<TBase>, FilterDefinition<TBase>> filter, bool prepend = false) where TBase : IEntity

Parameters

filter Func<FilterDefinitionBuilder<TBase>, FilterDefinition<TBase>>

b => b.Eq(x => x.Prop1, "some value")

prepend bool

Set to true if you want to prepend this global filter to your operation filters instead of being appended

Type Parameters

TBase

The type of the base class

SetGlobalFilterForBaseClass<TBase>(Expression<Func<TBase, bool>>, bool)

Specify a global filter to be applied to all operations performed with this DBContext

protected void SetGlobalFilterForBaseClass<TBase>(Expression<Func<TBase, bool>> filter, bool prepend = false) where TBase : IEntity

Parameters

filter Expression<Func<TBase, bool>>

b => b.Eq(x => x.Prop1, "some value")

prepend bool

Set to true if you want to prepend this global filter to your operation filters instead of being appended

Type Parameters

TBase

The type of the base class

SetGlobalFilterForInterface<TInterface>(string, bool)

Specify a global filter for all entity types that implements a given interface

protected void SetGlobalFilterForInterface<TInterface>(string jsonString, bool prepend = false)

Parameters

jsonString string

A JSON string filter definition to be applied

prepend bool

Set to true if you want to prepend this global filter to your operation filters instead of being appended

Type Parameters

TInterface

The interface type to target. Will throw if supplied argument is not an interface type

SetGlobalFilter<T>(FilterDefinition<T>, bool)

Specify a global filter to be applied to all operations performed with this DBContext

protected void SetGlobalFilter<T>(FilterDefinition<T> filter, bool prepend = false) where T : IEntity

Parameters

filter FilterDefinition<T>

A filter definition to be applied

prepend bool

Set to true if you want to prepend this global filter to your operation filters instead of being appended

Type Parameters

T

The type of Entity this global filter should be applied to

SetGlobalFilter<T>(Func<FilterDefinitionBuilder<T>, FilterDefinition<T>>, bool)

Specify a global filter to be applied to all operations performed with this DBContext

protected void SetGlobalFilter<T>(Func<FilterDefinitionBuilder<T>, FilterDefinition<T>> filter, bool prepend = false) where T : IEntity

Parameters

filter Func<FilterDefinitionBuilder<T>, FilterDefinition<T>>

b => b.Eq(x => x.Prop1, "some value")

prepend bool

Set to true if you want to prepend this global filter to your operation filters instead of being appended

Type Parameters

T

The type of Entity this global filter should be applied to

SetGlobalFilter<T>(Expression<Func<T, bool>>, bool)

Specify a global filter to be applied to all operations performed with this DBContext

protected void SetGlobalFilter<T>(Expression<Func<T, bool>> filter, bool prepend = false) where T : IEntity

Parameters

filter Expression<Func<T, bool>>

x => x.Prop1 == "some value"

prepend bool

Set to true if you want to prepend this global filter to your operation filters instead of being appended

Type Parameters

T

The type of Entity this global filter should be applied to

SetServiceProvider(IServiceProvider)

Initializes the ASP.NET Core Dependency Injection provider. Call this during application startup.

public void SetServiceProvider(IServiceProvider serviceProvider)

Parameters

serviceProvider IServiceProvider

The IServiceProvider instance

Sort<T>()

Exposes the mongodb Sort Definition Builder for a given type.

public static SortDefinitionBuilder<T> Sort<T>() where T : IEntity

Returns

SortDefinitionBuilder<T>

Type Parameters

T

Any class that implements IEntity

Transaction(ClientSessionOptions?, TransactionOptions?)

Creates a Transaction(ClientSessionOptions?, TransactionOptions?) instance (from the current DB instance) for performing operations in an atomic manner within a transaction.

public Transaction Transaction(ClientSessionOptions? options = null, TransactionOptions? transactionOptions = null)

Parameters

options ClientSessionOptions

Client session options for this transaction

transactionOptions TransactionOptions

options for the transaction

Returns

Transaction

UpdateAndGet<T>()

Starts an update-and-get command for the given entity type

public UpdateAndGet<T, T> UpdateAndGet<T>() where T : IEntity

Returns

UpdateAndGet<T, T>

Type Parameters

T

The type of entity

UpdateAndGet<T, TProjection>()

Starts an update-and-get command with projection support for the given entity type

public UpdateAndGet<T, TProjection> UpdateAndGet<T, TProjection>() where T : IEntity

Returns

UpdateAndGet<T, TProjection>

Type Parameters

T

The type of entity

TProjection

The type of the end result

Update<T>()

Starts an update command for the given entity type

public Update<T> Update<T>() where T : IEntity

Returns

Update<T>

Type Parameters

T

The type of entity

Watcher<T>(string)

Retrieves the 'change-stream' watcher instance for a given unique name. If an instance for the name does not exist, it will return a new instance. If an instance already exists, that instance will be returned.

public Watcher<T> Watcher<T>(string name) where T : IEntity

Parameters

name string

A unique name for the watcher of this entity type. Names can be duplicate among different entity types.

Returns

Watcher<T>

Type Parameters

T

The entity type to get a watcher for

Watchers<T>()

Returns all the watchers for a given entity type

public IEnumerable<Watcher<T>> Watchers<T>() where T : IEntity

Returns

IEnumerable<Watcher<T>>

Type Parameters

T

The entity type to get the watcher of

WithModifiedBy(ModifiedBy)

Gets a DB instance with it's ModifiedBy property set to the supplied value. Any operations performed with the returned instance will use the supplied audit data when storing/updating entities.

public DB WithModifiedBy(ModifiedBy modifiedBy)

Parameters

modifiedBy ModifiedBy

the audit data to use

Returns

DB