Interface IUnitOfWork
- Namespace
- Builvero.Application.Interfaces.Repositories
- Assembly
- Builvero.Application.dll
Defines the contract for the Unit of Work pattern, providing transaction management and bulk operations.
public interface IUnitOfWork
Remarks
The Unit of Work pattern ensures that all changes made to entities within a single business transaction are committed together, maintaining data consistency. It also provides bulk deletion capabilities.
Methods
Add<T>(T)
Adds a new entity to the context and ensures it's marked as Added. This is useful when adding entities through navigation properties to ensure they're correctly tracked as new entities rather than Modified.
void Add<T>(T entity) where T : class
Parameters
entityTThe entity to add.
Type Parameters
TThe entity type.
Remarks
This method ensures that the entity is tracked and marked as Added, even if it was previously tracked in a different state. This prevents EF Core from trying to UPDATE entities that should be INSERTed.
EnsureEntityNotModified<T>(T)
Ensures that an entity is not marked as Modified if it hasn't been explicitly modified. This is useful to prevent concurrency issues when only related entities are modified.
void EnsureEntityNotModified<T>(T entity) where T : class
Parameters
entityTThe entity to check and potentially reset to Unchanged state.
Type Parameters
TThe entity type.
Remarks
This method checks if the entity is tracked and marked as Modified, and if so, resets it to Unchanged state. This prevents EF Core from generating UPDATE statements for entities that haven't actually been modified.
RemoveRange<T>(IEnumerable<T>)
Marks a collection of entities for deletion in a single operation.
void RemoveRange<T>(IEnumerable<T> entities) where T : class
Parameters
entitiesIEnumerable<T>The collection of entities to mark for deletion.
Type Parameters
TThe entity type to remove.
Remarks
This method marks entities for deletion but does not immediately delete them from the database. The actual deletion occurs when SaveChangesAsync(CancellationToken) is called.
SaveChangesAsync(CancellationToken)
Saves all pending changes to the database asynchronously.
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
Parameters
cancellationTokenCancellationTokenCancellation token to cancel the operation.
Returns
Remarks
This method commits all pending changes (inserts, updates, deletes) made to entities tracked by the DbContext. Returns the number of affected records.