Table of Contents

Class DbContextBase

Namespace
NuvTools.Data.EntityFrameworkCore.Context
Assembly
NuvTools.Data.EntityFrameworkCore.dll

Abstract base class for DbContext implementations that provides common CRUD operations, transaction management, bulk operations, and execution strategies using the Result pattern.

public abstract class DbContextBase : DbContext, IInfrastructure<IServiceProvider>, IDbContextDependencies, IDbSetCache, IDbContextPoolable, IResettableService, IDisposable, IAsyncDisposable, IDbContextCommands, IDbContextWithListCommands
Inheritance
DbContextBase
Implements
Inherited Members
Extension Methods

Remarks

This class implements IDbContextCommands and IDbContextWithListCommands to provide a consistent interface for database operations across the application.

Constructors

DbContextBase()

Initializes a new instance of the DbContextBase class.

protected DbContextBase()

DbContextBase(DbContextOptions)

Initializes a new instance of the DbContextBase class with the specified options.

protected DbContextBase(DbContextOptions options)

Parameters

options DbContextOptions

The options to be used by the DbContext.

Properties

CurrentTransaction

Gets the current active transaction, or null if no transaction is active.

public IDbContextTransaction? CurrentTransaction { get; }

Property Value

IDbContextTransaction

Methods

AcquireTransactionLockAsync(string, CancellationToken)

Acquires an exclusive, database-wide lock identified by name, held until the current transaction commits or rolls back. Callers competing for the same name are serialized; different names never block each other.

public Task AcquireTransactionLockAsync(string name, CancellationToken cancellationToken = default)

Parameters

name string

Lock name. Identifies what is being serialized, e.g. "contract-number:53".

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task

A task that completes once the lock is held.

Remarks

Use it to serialize a read-then-write that the schema alone cannot make atomic — allocating the next value of a per-tenant sequence, for instance, where every writer reads the same maximum and collides on a unique index. It is an advisory lock: it guards nothing by itself, only callers that ask for the same name.

A transaction must be active (see BeginTransactionAsync(CancellationToken)). Without one the lock is released as soon as the statement ends and protects nothing, so the call throws instead.

The statement itself lives in the provider package — pg_advisory_xact_lock in NuvTools.Data.EntityFrameworkCore.PostgreSQL, sp_getapplock (LockOwner Transaction) in NuvTools.Data.EntityFrameworkCore.SqlServer — behind IDbContextTransactionLock, and is registered by that package's AddDatabase helpers. With no such package in play (an in-memory context built by hand in a test) there is nothing to serialize and the call does nothing.

AddAndSaveAsync<TEntity, TKey>(TEntity, CancellationToken)

Adds a new entity to the database and saves changes, returning the entity's primary key.

public Task<IResult<TKey>> AddAndSaveAsync<TEntity, TKey>(TEntity entity, CancellationToken cancellationToken = default) where TEntity : class

Parameters

entity TEntity

The entity to add.

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task<IResult<TKey>>

A task that represents the asynchronous operation, containing the result with the primary key.

Type Parameters

TEntity

The type of the entity.

TKey

The type of the primary key.

AddAndSaveWithCompositeKeyAsync<TEntity>(TEntity, CancellationToken)

Adds a new entity with a composite key to the database and saves changes.

public Task<IResult<object[]>> AddAndSaveWithCompositeKeyAsync<TEntity>(TEntity entity, CancellationToken cancellationToken = default) where TEntity : class

Parameters

entity TEntity

The entity to add.

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task<IResult<object[]>>

A task that represents the asynchronous operation, containing the result with the composite key values.

Type Parameters

TEntity

The type of the entity.

AddOrRemoveFromListAsync<TEntity, TKey>(IEnumerable<TEntity>, Func<TEntity, TKey>, Expression<Func<TEntity, bool>>?, CancellationToken)

Synchronizes a DbSet with a provided list by adding or removing entities, without updating any entities.

public Task<IResult> AddOrRemoveFromListAsync<TEntity, TKey>(IEnumerable<TEntity> entities, Func<TEntity, TKey> keySelector, Expression<Func<TEntity, bool>>? filter = null, CancellationToken cancellationToken = default) where TEntity : class where TKey : notnull

Parameters

entities IEnumerable<TEntity>

The list of entities to synchronize with the database.

keySelector Func<TEntity, TKey>

A function to select the key for matching entities.

filter Expression<Func<TEntity, bool>>

An optional filter predicate to apply to the database entities.

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task<IResult>

Type Parameters

TEntity

The type of the entity.

TKey

The type of the key used to uniquely identify entities.

Examples

await context.AddOrRemoveFromListAsync( updatedOrders, o => o.OrderId, o => o.IsPending );

Remarks

This method adds entities in the list that are not in the database and removes entities in the database that are not in the list. It does not update any entities.

AddOrUpdateFromListAsync<TEntity, TKey>(IEnumerable<TEntity>, Func<TEntity, TKey>, Expression<Func<TEntity, bool>>?, CancellationToken)

Synchronizes a DbSet with a provided list by adding or updating entities, without removing any entities.

public Task<IResult> AddOrUpdateFromListAsync<TEntity, TKey>(IEnumerable<TEntity> entities, Func<TEntity, TKey> keySelector, Expression<Func<TEntity, bool>>? filter = null, CancellationToken cancellationToken = default) where TEntity : class where TKey : notnull

Parameters

entities IEnumerable<TEntity>

The list of entities to synchronize with the database.

keySelector Func<TEntity, TKey>

A function to select the key for matching entities.

filter Expression<Func<TEntity, bool>>

An optional filter predicate to apply to the database entities.

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task<IResult>

Type Parameters

TEntity

The type of the entity.

TKey

The type of the key used to uniquely identify entities.

Examples

await context.AddOrUpdateFromListAsync( updatedProducts, p => p.ProductCode, p => p.IsActive );

Remarks

This method adds entities in the list that are not in the database and updates entities that exist in both. It does not remove any entities from the database.

BeginTransactionAsync(CancellationToken)

Begins a new database transaction asynchronously.

public Task<IDbContextTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task<IDbContextTransaction>

A task that represents the asynchronous operation, containing the database transaction.

CommitTransactionAsync(CancellationToken)

Commits the current transaction asynchronously.

public Task CommitTransactionAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task

A task that represents the asynchronous operation.

ExecuteWithStrategyAsync(Func<CancellationToken, Task>, CancellationToken)

Executes an action within the database execution strategy for connection resiliency.

public Task ExecuteWithStrategyAsync(Func<CancellationToken, Task> action, CancellationToken cancellationToken = default)

Parameters

action Func<CancellationToken, Task>

The action to execute within the strategy.

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task

A task that represents the asynchronous operation.

See Also

ExecuteWithStrategyAsync<T>(Func<CancellationToken, Task<T>>, CancellationToken)

Executes an action within the database execution strategy for connection resiliency and returns a result.

public Task<T> ExecuteWithStrategyAsync<T>(Func<CancellationToken, Task<T>> action, CancellationToken cancellationToken = default)

Parameters

action Func<CancellationToken, Task<T>>

The action to execute within the strategy.

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task<T>

A task that represents the asynchronous operation, containing the result of the action.

Type Parameters

T

The type of the result returned by the action.

See Also

RemoveAndSaveAsync<TEntity>(params object[])

Removes an entity from the database and saves changes.

public Task<IResult> RemoveAndSaveAsync<TEntity>(params object[] keyValues) where TEntity : class

Parameters

keyValues object[]

The primary key values of the entity to remove.

Returns

Task<IResult>

A task that represents the asynchronous operation, containing the result of the remove operation.

Type Parameters

TEntity

The type of the entity.

RemoveAndSaveAsync<TEntity>(object[], CancellationToken)

Removes an entity from the database and saves changes.

public Task<IResult> RemoveAndSaveAsync<TEntity>(object[] keyValues, CancellationToken cancellationToken = default) where TEntity : class

Parameters

keyValues object[]

The primary key values of the entity to remove.

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task<IResult>

A task that represents the asynchronous operation, containing the result of the remove operation.

Type Parameters

TEntity

The type of the entity.

RollbackTransactionAsync(CancellationToken)

Rolls back the current transaction asynchronously.

public Task RollbackTransactionAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task

A task that represents the asynchronous operation.

SyncFromListAsync<TEntity, TKey>(IEnumerable<TEntity>, Func<TEntity, TKey>, Expression<Func<TEntity, bool>>?, CancellationToken)

Synchronizes a DbSet with a provided list by adding, updating, or removing entities.

public Task<IResult> SyncFromListAsync<TEntity, TKey>(IEnumerable<TEntity> entities, Func<TEntity, TKey> keySelector, Expression<Func<TEntity, bool>>? filter = null, CancellationToken cancellationToken = default) where TEntity : class where TKey : notnull

Parameters

entities IEnumerable<TEntity>

The list of entities to synchronize with the database.

keySelector Func<TEntity, TKey>

A function to select the key for matching entities.

filter Expression<Func<TEntity, bool>>

An optional filter predicate to apply to the database entities.

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task<IResult>

Type Parameters

TEntity

The type of the entity.

TKey

The type of the key used to uniquely identify entities.

Examples

await context.SyncFromListAsync( updatedEmployees, e => e.Id, e => e.IsActive );

Remarks

This method adds entities in the list that are not in the database, updates entities that exist in both, and removes entities in the database that are not in the list.

UpdateAndSaveAsync<TEntity>(TEntity, params object[])

Updates an existing entity in the database and saves changes.

public Task<IResult> UpdateAndSaveAsync<TEntity>(TEntity entity, params object[] keyValues) where TEntity : class

Parameters

entity TEntity

The entity with updated values.

keyValues object[]

The primary key values of the entity to update.

Returns

Task<IResult>

A task that represents the asynchronous operation, containing the result of the update operation.

Type Parameters

TEntity

The type of the entity.

UpdateAndSaveAsync<TEntity>(TEntity, object[], CancellationToken)

Updates an existing entity in the database and saves changes.

public Task<IResult> UpdateAndSaveAsync<TEntity>(TEntity entity, object[] keyValues, CancellationToken cancellationToken = default) where TEntity : class

Parameters

entity TEntity

The entity with updated values.

keyValues object[]

The primary key values of the entity to update.

cancellationToken CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

Task<IResult>

A task that represents the asynchronous operation, containing the result of the update operation.

Type Parameters

TEntity

The type of the entity.