Boost Your .NET Projects with Spargine: Simplify Entity Framework Core with DbContextExtensions

Spargine is a collection of open-source assemblies and NuGet packages designed for .NET 10, which I have been developing and maintaining since the release of .NET Framework 2. These assemblies are not only a core part of my projects but are also actively deployed in production environments across several companies I collaborate with.

Get Spargine

You can access the source code and NuGet packages here:

Repeated data-access code is more than just clutter. When the same Entity Framework Core patterns are copied across repositories, services, and projects, there are more places for behavior to diverge, bugs to appear, and maintenance costs to grow.

A better approach is to centralize common operations behind well-tested, reusable methods.

That is where DbContextExtensions, available in the DotNetTips.Spargine.Extensions project and NuGet package, can help.

DbContextExtensions provides extension methods for Entity Framework Core’s DbContext that reduce repetitive code and provide common data-access patterns through a consistent, async-first API. The extensions cover adding and deleting collections of entities, transaction management, change tracking, record-count queries, and existence checks.

Instead of rewriting these patterns throughout an application, Spargine lets you keep them consistent and reusable.

Methods

AddAndSaveAsync<T>(IEnumerable<T> entities, CancellationToken cancellationToken)

Adds a collection of entities to the DbContext and asynchronously saves the changes to the database.

The method combines AddRangeAsync() and SaveChangesAsync() into a single operation and returns the number of state entries written to the database.

This is useful when an application frequently adds collections of entities and immediately persists them.

DeleteAndSaveAsync<T>(IEnumerable<T> entities, CancellationToken cancellationToken)

Removes a collection of entities from the DbContext and asynchronously saves the changes to the database.

The method combines RemoveRange() with SaveChangesAsync() and returns the number of state entries written to the database.

This eliminates another common pattern that would otherwise need to be repeated throughout the data-access layer.

ExecuteInTransactionAsync(Func<DbContext, CancellationToken, Task> action, CancellationToken cancellationToken)

Executes an asynchronous operation inside a database transaction.

The method begins the transaction, executes the supplied delegate, and commits the transaction when the operation completes successfully. If an exception occurs, the transaction is rolled back and the exception is rethrown.

This provides a consistent way to wrap multiple database operations in a transaction while keeping transaction-management code out of application logic.

The supplied delegate remains responsible for performing the required Entity Framework Core operations, including calling SaveChangesAsync() when appropriate.

GetChangedEntities<T>(EntityState state)

Returns all tracked entities of the specified type that currently match the supplied EntityState.

For example, it can be used to retrieve entities currently marked as:

  • Added
  • Modified
  • Deleted
  • Unchanged
  • Detached

The method works with the DbContext change tracker rather than querying the database and returns the matching entities as a read-only collection.

This can be useful for auditing, validation, diagnostics, logging, or other operations that need to examine changes before they are persisted.

GetRecordCountAsync<T>(CancellationToken cancellationToken)

Asynchronously returns the total number of records for the specified entity type.

This provides a concise wrapper around the common Entity Framework Core CountAsync() pattern.

GetRecordCountAsync<T>(Expression<Func<T, bool>> predicate, CancellationToken cancellationToken)

Asynchronously returns the number of records matching the supplied predicate.

For example, an application could use this overload to determine how many orders are pending, how many users are active, or how many records meet another application-specific condition.

HasChanges()

Determines whether the current DbContext contains any unsaved changes.

The method checks the Entity Framework Core change tracker and returns true when changes are waiting to be persisted.

This can be useful before calling SaveChanges() or SaveChangesAsync(), as well as for diagnostics, validation, or workflows that need to know whether anything has changed.

HasRecordsAsync<T>(CancellationToken cancellationToken)

Asynchronously determines whether any records exist for the specified entity type.

This provides a simple existence check without requiring application code to repeatedly implement the same AnyAsync() pattern.

HasRecordsAsync<T>(Expression<Func<T, bool>> predicate, CancellationToken cancellationToken)

Asynchronously determines whether any records matching the supplied predicate exist.

This makes common conditional existence checks concise and reusable while still allowing the filtering logic to be expressed through a standard LINQ expression.

Summary

Entity Framework Core already provides a powerful API, but real-world applications often end up repeating the same small data-access patterns throughout the codebase.

DbContextExtensions in Spargine brings those patterns together behind a focused set of reusable extension methods.

With helpers for adding and deleting entity collections, executing transactional operations, examining the change tracker, counting records, and checking whether records exist, developers can reduce repetitive EF Core code while making data-access behavior more consistent across a solution.

Less boilerplate means fewer places to maintain, fewer opportunities for implementations to drift apart, and code that more clearly communicates what it is trying to accomplish. That is exactly the kind of repetitive infrastructure code that should be written once, tested once, and reused everywhere.

Get Involved!

The success of open-source projects like Spargine relies on community contributions. If you find these updates useful or have ideas for further improvements, I encourage you to contribute by:

  • Submitting pull requests
  • Reporting issues
  • Suggesting new features

Your input is invaluable in making Spargine an even more powerful tool for the .NET community.

If you are interested in contributing or have any questions, feel free to contact me via email at dotnetdave@live.com. Your support and collaboration are greatly appreciated!

Thank you, and happy coding!

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copyrighted and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a Reply