Class DB
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
sourceDB
Properties
Default
Gets the default DB instance when previously initialized.
public static DB Default { get; }
Property Value
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
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
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
settingsMongoClientSettingsA MongoClientSettings object
Returns
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
Returns
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
namestringThe name of the database to mark as the new default database
settingsMongoClientSettingsThe 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
Type Parameters
TThe 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
TAny 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
filterFilterDefinition<T>A filter definition
cancellationCancellationTokenAn optional cancellation token
optionsCountOptionsAn optional CountOptions object
ignoreGlobalFiltersboolSet to true if you'd like to ignore any global filters for this operation
Returns
Type Parameters
TThe 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
filterFunc<FilterDefinitionBuilder<T>, FilterDefinition<T>>f => f.Eq(x => x.Prop, Value) & f.Gt(x => x.Prop, Value)
cancellationCancellationTokenAn optional cancellation token
optionsCountOptionsAn optional CountOptions object
ignoreGlobalFiltersboolSet to true if you'd like to ignore any global filters for this operation
Returns
Type Parameters
TThe 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
expressionExpression<Func<T, bool>>A lambda expression for getting the count for a subset of the data
cancellationCancellationTokenAn optional cancellation token
optionsCountOptionsAn optional CountOptions object
ignoreGlobalFiltersboolSet to true if you'd like to ignore any global filters for this operation
Returns
Type Parameters
TThe 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
cancellationCancellationTokenAn optional cancellation token
Returns
Type Parameters
TThe 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
cancellationCancellationTokenAn optional cancellation token
Returns
Type Parameters
TThe 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
optionsAction<CreateCollectionOptions<T>>The options to use for collection creation
cancellationCancellationTokenAn optional cancellation token
sessionIClientSessionHandleAn optional session if using within a transaction
Returns
Type Parameters
TThe 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
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
filterFilterDefinition<T>A filter definition for matching entities to delete.
cancellationCancellationTokenAn optional cancellation token
collationCollationAn optional collation object
Returns
- Task<DeleteResult>
Type Parameters
TAny 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
IDsIEnumerable<object>An IEnumerable of entity IDs
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<DeleteResult>
Type Parameters
TAny 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
entitiesIEnumerable<T>An IEnumerable of entities
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<DeleteResult>
Type Parameters
TAny 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
filterFunc<FilterDefinitionBuilder<T>, FilterDefinition<T>>f => f.Eq(x => x.Prop, Value) & f.Gt(x => x.Prop, Value)
cancellationCancellationTokenAn optional cancellation token
collationCollationAn optional collation object
Returns
- Task<DeleteResult>
Type Parameters
TAny 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
expressionExpression<Func<T, bool>>A lambda expression for matching entities to delete.
cancellationCancellationTokenAn optional cancellation token
collationCollationAn optional collation object
Returns
- Task<DeleteResult>
Type Parameters
TAny 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
IDobjectThe Id of the entity to delete
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<DeleteResult>
Type Parameters
TAny 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
entityTThe entity to delete
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<DeleteResult>
Type Parameters
TAny 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
TAny Entity that implements IEntity interface
TPropertyThe 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
sessionIClientSessionHandleAn optional session if using within a transaction
Returns
Type Parameters
TThe 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
TAny 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
IDobjectThe ID to set on the returned instance
Returns
- T
Type Parameters
TAny 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
IDstringThe ID of the file entity
Returns
- DataStreamer<T>
Type Parameters
TThe 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
TAny 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
TAny 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
TAny class that implements IEntity
TProjectionThe 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
searchTypeSearchThe type of text matching to do
searchTermstringThe search term
caseSensitiveboolCase sensitivity of the search (optional)
diacriticSensitiveboolDiacritic sensitivity of the search (optional)
languagestringThe language for the search (optional)
optionsAggregateOptionsOptions 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
optionsAggregateOptionsThe options for the aggregation. This is not required.
Returns
- IAggregateFluent<T>
Type Parameters
TThe 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
NearCoordinatesCoordinates2DThe coordinates from which to find documents from
DistanceFieldExpression<Func<T, object>>x => x.Distance
SphericalboolCalculate distances using spherical geometry or not
MaxDistanceint?The maximum distance in meters from the center point that the documents can be
MinDistanceint?The minimum distance in meters from the center point that the documents can be
Limitint?The maximum number of documents to return
QueryBsonDocumentLimits the results to the documents that match the query
DistanceMultiplierint?The factor to multiply all distances returned by the query
IncludeLocationsExpression<Func<T, object>>Specify the output field to store the point used to calculate the distance
IndexKeystringoptionsAggregateOptionsThe options for the aggregation. This is not required.
Returns
- IAggregateFluent<T>
Type Parameters
TThe 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
TAny 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
dbNamestringName of the database
clientSettingsMongoClientSettingsA MongoClientSettings object
databaseSettingsMongoDatabaseSettingsThe database settings to create the database with
skipNetworkPingboolShould we ping the database
Returns
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
entitiesIEnumerable<T>The entities to persist
cancellationCancellationTokenAnd optional cancellation token
Returns
- Task<BulkWriteResult<T>>
Type Parameters
TAny 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
entityTThe instance to persist
cancellationCancellationTokenAnd optional cancellation token
Returns
Type Parameters
TAny 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
dbNamestringThe name of the database to retrieve
settingsMongoClientSettingsThe host we want the instance from
Returns
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
MigrateAsync<T>()
Discover and run migrations from the same assembly as the specified type.
public Task MigrateAsync<T>() where T : class
Returns
Type Parameters
TA 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
migrationsIEnumerable<IMigration>The collection of migrations to execute
Returns
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
sequenceNamestringThe name of the sequence to get the next number for
cancellationCancellationTokenAn optional cancellation token
Returns
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
cancellationCancellationTokenAn optional cancellation token
Returns
Type Parameters
TThe 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
TAny 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
TAny 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
TAny 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
TAny class that implements IEntity
TProjectionThe 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
templateTemplate<T, TResult>A 'Template' object with tags replaced
cancellationCancellationTokenAn optional cancellation token
optionsAggregateOptionsThe options for the aggregation. This is not required.
Returns
Type Parameters
TAny class that implements IEntity
TResultThe 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
templateTemplate<T, TResult>A 'Template' object with tags replaced
cancellationCancellationTokenAn optional cancellation token
optionsAggregateOptionsThe options for the aggregation. This is not required.
Returns
- Task<IAsyncCursor<TResult>>
Type Parameters
TAny class that implements IEntity
TResultThe 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
templateTemplate<T, TResult>A 'Template' object with tags replaced
cancellationCancellationTokenAn optional cancellation token
optionsAggregateOptionsThe options for the aggregation. This is not required.
Returns
- Task<TResult>
Type Parameters
TAny class that implements IEntity
TResultThe 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
templateTemplate<T, TResult>A 'Template' object with tags replaced
cancellationCancellationTokenAn optional cancellation token
optionsAggregateOptionsThe options for the aggregation. This is not required.
Returns
- Task<TResult>
Type Parameters
TAny class that implements IEntity
TResultThe 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
TAny 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
optionsAggregateOptionsThe aggregate options
Returns
- IQueryable<T>
Type Parameters
TThe 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
TAny 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
entitiesIEnumerable<T>The entities to persist
cancellationCancellationTokenAnd optional cancellation token
Returns
- Task<BulkWriteResult<T>>
Type Parameters
TAny 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
entityTThe instance to persist
cancellationCancellationTokenAnd optional cancellation token
Returns
Type Parameters
TAny 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
entitiesIEnumerable<T>The batch of entities to save
propNamesIEnumerable<string>new List { "PropOne", "PropTwo" }
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<BulkWriteResult<T>>
Type Parameters
TAny 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
entitiesIEnumerable<T>The batch of entities to save
membersExpression<Func<T, object>>x => new { x.PropOne, x.PropTwo }
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<BulkWriteResult<T>>
Type Parameters
TAny 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
entityTThe entity to save
propNamesIEnumerable<string>new List { "PropOne", "PropTwo" }
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<UpdateResult>
Type Parameters
TAny 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
entityTThe entity to save
membersExpression<Func<T, object>>x => new { x.PropOne, x.PropTwo }
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<UpdateResult>
Type Parameters
TAny 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
entitiesIEnumerable<T>The batch of entities to save
propNamesIEnumerable<string>new List { "PropOne", "PropTwo" }
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<BulkWriteResult<T>>
Type Parameters
TAny 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
entitiesIEnumerable<T>The batch of entities to save
membersExpression<Func<T, object>>x => new { x.PropOne, x.PropTwo }
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<BulkWriteResult<T>>
Type Parameters
TAny 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
entityTThe entity to save
propNamesIEnumerable<string>new List { "PropOne", "PropTwo" }
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<UpdateResult>
Type Parameters
TAny 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
entityTThe entity to save
membersExpression<Func<T, object>>x => new { x.PropOne, x.PropTwo }
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<UpdateResult>
Type Parameters
TAny 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
entityTThe entity to save
cancellationCancellationTokenAn optional cancellation token
Returns
- Task<UpdateResult>
Type Parameters
TAny 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
typeTypeThe type of Entity this global filter should be applied to
jsonStringstringA JSON string filter definition to be applied
prependboolSet 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
filterFilterDefinition<TBase>A filter definition to be applied
prependboolSet to true if you want to prepend this global filter to your operation filters instead of being appended
Type Parameters
TBaseThe 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
filterFunc<FilterDefinitionBuilder<TBase>, FilterDefinition<TBase>>b => b.Eq(x => x.Prop1, "some value")
prependboolSet to true if you want to prepend this global filter to your operation filters instead of being appended
Type Parameters
TBaseThe 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
filterExpression<Func<TBase, bool>>b => b.Eq(x => x.Prop1, "some value")
prependboolSet to true if you want to prepend this global filter to your operation filters instead of being appended
Type Parameters
TBaseThe 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
jsonStringstringA JSON string filter definition to be applied
prependboolSet to true if you want to prepend this global filter to your operation filters instead of being appended
Type Parameters
TInterfaceThe 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
filterFilterDefinition<T>A filter definition to be applied
prependboolSet to true if you want to prepend this global filter to your operation filters instead of being appended
Type Parameters
TThe 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
filterFunc<FilterDefinitionBuilder<T>, FilterDefinition<T>>b => b.Eq(x => x.Prop1, "some value")
prependboolSet to true if you want to prepend this global filter to your operation filters instead of being appended
Type Parameters
TThe 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
filterExpression<Func<T, bool>>x => x.Prop1 == "some value"
prependboolSet to true if you want to prepend this global filter to your operation filters instead of being appended
Type Parameters
TThe 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
serviceProviderIServiceProviderThe 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
TAny 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
optionsClientSessionOptionsClient session options for this transaction
transactionOptionsTransactionOptionsoptions for the transaction
Returns
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
TThe 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
TThe type of entity
TProjectionThe 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
TThe 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
namestringA unique name for the watcher of this entity type. Names can be duplicate among different entity types.
Returns
- Watcher<T>
Type Parameters
TThe 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
TThe 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
modifiedByModifiedBythe audit data to use