Skip to content

Commit e29d719

Browse files
committed
Separate context execution from DAL operations
- add a provider-independent database context executor abstraction - support borrowed and provider-owned context scopes - expose active transaction state through IDbContext - add TryRollback for non-throwing rollback attempts - remove context creation and table metadata from DalBase - rename database context execution methods - update public API documentation
1 parent 9401d60 commit e29d719

6 files changed

Lines changed: 172 additions & 182 deletions

File tree

‎README.md‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,43 @@
11
# NuExt.System.Data
22

3-
`NuExt.System.Data` provides high-level data access utilities for .NET, including extensions for `DataReader`, `DataRow`, and `DataTable`, lightweight DAL infrastructure, database context abstractions, and a provider-independent migration framework.
3+
`NuExt.System.Data` provides a lightweight and extensible foundation for data access in .NET applications. It combines practical ADO.NET extensions, reusable DAL and database context abstractions, explicit transaction management, and provider-independent database migrations with validated history tracking.
44

55
[![NuGet](https://img.shields.io/nuget/v/NuExt.System.Data.svg)](https://www.nuget.org/packages/NuExt.System.Data)
66
[![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-blue)](https://deepwiki.com/nu-ext/NuExt.System.Data)
77
[![Build](https://github.com/nu-ext/NuExt.System.Data/actions/workflows/ci.yml/badge.svg)](https://github.com/nu-ext/NuExt.System.Data/actions/workflows/ci.yml)
88
[![License](https://img.shields.io/github/license/nu-ext/NuExt.System.Data?label=license)](https://github.com/nu-ext/NuExt.System.Data/blob/main/LICENSE)
99
[![Downloads](https://img.shields.io/nuget/dt/NuExt.System.Data.svg)](https://www.nuget.org/packages/NuExt.System.Data)
1010

11-
### Features
11+
## Features
1212

1313
- **ADO.NET Extensions**: Provides helpers for reading, converting, and manipulating data through `DataReader`, `DataRow`, and `DataTable`.
1414
- **DAL Infrastructure**: Includes lightweight base classes and database context abstractions for implementing data access layers.
1515
- **Database Migrations**: Provides provider-independent migration orchestration with ordered execution, validated migration history, optional version metadata, cancellation support, and provider-specific execution contexts.
1616

17-
### Commonly Used Types
17+
## DAL Context Ownership
1818

19-
- **`System.Data.DalBase<TDbContext>`**: Base class for Data Access Layer (DAL) implementations.
19+
The DAL infrastructure supports two execution models:
20+
21+
- **Owned context**: When no database context is provided, the provider-specific executor creates and owns the context. It manages the connection, transaction, commit or rollback, and resource cleanup.
22+
- **Borrowed context**: When an existing database context is provided, the DAL participates in the caller's unit of work without committing, rolling back, or disposing the context.
23+
24+
This allows individual DAL operations to run independently while also supporting coordinated operations across multiple DAL components within the same transaction.
25+
26+
## Commonly Used Types
27+
28+
- **`System.Data.DalBase<TDbContext>`**: Base class for DAL implementations that supports borrowed contexts and provider-managed owned context scopes.
2029
- **`System.Data.DataReaderExtensions`**: Provides extension methods for data reader operations.
2130
- **`System.Data.DataRowExtensions`**: Provides extension methods for data row operations.
2231
- **`System.Data.DataTableExtensions`**: Provides extension methods for data table operations.
2332
- **`System.Data.DbMigration<TContext>`**: Base class for defining ordered database schema and data migrations.
2433
- **`System.Data.DbMigrationContext`**: Base class for provider-specific migration execution contexts.
25-
- **`System.Data.DbMigrator<TContext>`**: Validates migration configuration and history, and applies pending migrations.
26-
- **`System.Data.IDbMigrationExecutor<TContext>`**: Defines provider-specific migration execution and
34+
- **`System.Data.DbMigrator<TContext>`**: Validates migration configuration and applied history, and executes pending migrations.
35+
- **`System.Data.IDbContext`**: Defines transaction state and lifecycle operations for database contexts.
36+
- **`System.Data.IDbContextExecutor<TDbContext>`**: Defines provider-specific ownership and execution of database context scopes.
37+
- **`System.Data.IDbMigrationExecutor<TContext>`**: Defines provider-specific migration execution and transaction handling.
38+
- **`System.Data.IDbMigrationHistory<TContext>`**: Defines storage operations for applied migration history.
2739

28-
### Installation
40+
## Installation
2941

3042
Via [NuGet](https://www.nuget.org/):
3143

@@ -39,7 +51,11 @@ Or via Visual Studio:
3951
2. Search for `NuExt.System.Data`.
4052
3. Click "Install".
4153

42-
### Usage Examples
54+
### Compatibility
55+
56+
**.NET Standard 2.0+, .NET 8/9/10 and .NET Framework 4.6.2+**
57+
58+
## Usage Examples
4359

4460
For a complete provider implementation and migration example, see:
4561

‎src/System/Data/DalBase`1.cs‎

Lines changed: 52 additions & 173 deletions
Original file line numberDiff line numberDiff line change
@@ -1,223 +1,102 @@
11
using System.ComponentModel;
2-
using System.Diagnostics.CodeAnalysis;
32

43
namespace System.Data;
54

65
/// <summary>
7-
/// Represents an abstract base class for Data Access Layer (DAL) operations,
8-
/// providing a framework for database context management and execution of database-related actions.
6+
/// Provides database context execution for Data Access Layer operations.
97
/// </summary>
108
/// <typeparam name="TDbContext">The type of the database context.</typeparam>
119
public abstract class DalBase<TDbContext> : Disposable where TDbContext : IDbContext
1210
{
13-
protected DalBase()
14-
{
15-
}
16-
17-
#region Properties
18-
19-
/// <summary>
20-
/// Gets the list of columns relevant to the specific implementation of the derived class.
21-
/// This property should be overridden in derived classes to specify the columns of the database table that the class interacts with.
22-
/// </summary>
23-
protected abstract string[] Columns { get; }
11+
private readonly IDbContextExecutor<TDbContext> _executor;
2412

2513
/// <summary>
26-
/// Gets the name of the table associated with the specific implementation of the derived class.
27-
/// This property should be overridden in derived classes to specify the name of the database table that the class interacts with.
14+
/// Initializes a new instance of the <see cref="DalBase{TDbContext}"/> class.
2815
/// </summary>
29-
protected abstract string TableName { get; }
30-
31-
#endregion
32-
33-
#region Methods
34-
35-
/// <summary>
36-
/// Creates and initializes an instance of the database context.
37-
/// </summary>
38-
/// <returns>An instance of <typeparamref name="TDbContext"/>.</returns>
39-
protected abstract TDbContext CreateDbContext();
40-
41-
/// <summary>
42-
/// Attempts to create and assign a new instance of the database context if it is not already initialized.
43-
/// </summary>
44-
/// <param name="context">Reference to the database context.</param>
45-
/// <returns><see langword="true"/> if a new context was created; otherwise, <see langword="false"/>.</returns>
46-
protected bool TryCreateDbContext([NotNull] ref TDbContext? context)
16+
/// <param name="executor">The database context executor.</param>
17+
/// <exception cref="ArgumentNullException"><paramref name="executor"/> is <see langword="null"/>.</exception>
18+
protected DalBase(IDbContextExecutor<TDbContext> executor)
4719
{
48-
if (context != null) return false;
49-
context = CreateDbContext();
50-
return true;
20+
_executor = executor ?? throw new ArgumentNullException(nameof(executor));
5121
}
5222

23+
#region Methods
24+
5325
/// <summary>
54-
/// Executes an action within a database context, ensuring that the context is managed (created, committed, or rolled back) accordingly.
26+
/// Executes the specified action using an existing database context or an owned context created by the executor.
5527
/// </summary>
56-
/// <param name="context">Optional existing context.</param>
57-
/// <param name="action">The action to perform within the context.</param>
58-
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
59-
/// <returns>A <see cref="ValueTask"/> representing the asynchronous operation.</returns>
60-
/// <exception cref="ArgumentNullException">
61-
/// Thrown if <paramref name="action"/> is null.
62-
/// </exception>
63-
protected virtual ValueTask TryExecuteInDbContextAsync(TDbContext? context, Action<TDbContext> action, CancellationToken cancellationToken = default)
28+
/// <param name="context">An optional existing database context.</param>
29+
/// <param name="action">The action to execute.</param>
30+
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
31+
/// <returns>A task that represents the operation.</returns>
32+
/// <exception cref="ArgumentNullException"><paramref name="action"/> is <see langword="null"/>.</exception>
33+
protected ValueTask ExecuteInDbContextAsync(TDbContext? context, Action<TDbContext> action, CancellationToken cancellationToken = default)
6434
{
6535
ArgumentNullException.ThrowIfNull(action);
6636
cancellationToken.ThrowIfCancellationRequested();
37+
CheckDisposed();
6738

68-
bool contextTaken = TryCreateDbContext(ref context);
69-
try
39+
if (context is null)
7040
{
71-
action(context);
72-
if (contextTaken)
73-
{
74-
context.Commit();
75-
}
76-
return default;
77-
}
78-
catch
79-
{
80-
if (contextTaken)
81-
{
82-
context.Rollback();
83-
}
84-
throw;
85-
}
86-
finally
87-
{
88-
if (contextTaken)
89-
{
90-
context.Dispose();
91-
}
41+
return _executor.ExecuteAsync(action, cancellationToken);
9242
}
43+
44+
action(context);
45+
return default;
9346
}
9447

9548
/// <summary>
96-
/// Asynchronously executes a function within a database context, ensuring that the context is managed (created, committed, or rolled back) accordingly.
49+
/// Executes the specified asynchronous action using an existing database context or an owned context created by the executor.
9750
/// </summary>
98-
/// <param name="context">Optional existing context.</param>
99-
/// <param name="action">The asynchronous function to perform within the context.</param>
100-
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
101-
/// <returns>A <see cref="ValueTask"/> representing the asynchronous operation.</returns>
102-
/// <exception cref="ArgumentNullException">
103-
/// Thrown if <paramref name="action"/> is null.
104-
/// </exception>
105-
protected virtual async ValueTask TryExecuteInDbContextAsync(TDbContext? context, Func<TDbContext, ValueTask> action, CancellationToken cancellationToken = default)
51+
/// <param name="context">An optional existing database context.</param>
52+
/// <param name="action">The asynchronous action to execute.</param>
53+
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
54+
/// <returns>A task that represents the asynchronous operation.</returns>
55+
/// <exception cref="ArgumentNullException"><paramref name="action"/> is <see langword="null"/>.</exception>
56+
protected ValueTask ExecuteInDbContextAsync(TDbContext? context, Func<TDbContext, ValueTask> action, CancellationToken cancellationToken = default)
10657
{
10758
ArgumentNullException.ThrowIfNull(action);
10859
cancellationToken.ThrowIfCancellationRequested();
60+
CheckDisposed();
10961

110-
bool contextTaken = TryCreateDbContext(ref context);
111-
try
112-
{
113-
await action(context);
114-
if (contextTaken)
115-
{
116-
context.Commit();
117-
}
118-
}
119-
catch
120-
{
121-
if (contextTaken)
122-
{
123-
context.Rollback();
124-
}
125-
throw;
126-
}
127-
finally
128-
{
129-
if (contextTaken)
130-
{
131-
context.Dispose();
132-
}
133-
}
62+
return context is null ? _executor.ExecuteAsync(action, cancellationToken) : action(context);
13463
}
13564

13665
/// <summary>
137-
/// Executes a function within a database context and returns a result, ensuring that the context is managed (created, committed, or rolled back) accordingly.
66+
/// Executes the specified function using an existing database context or an owned context created by the executor.
13867
/// </summary>
139-
/// <typeparam name="T">The type of the result produced by the function.</typeparam>
140-
/// <param name="context">Optional existing context.</param>
141-
/// <param name="func">The function to perform within the context.</param>
142-
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
143-
/// <returns>A <see cref="ValueTask{T}"/> containing the result of the function.</returns>
144-
/// <exception cref="ArgumentNullException">
145-
/// Thrown if <paramref name="func"/> is null.
146-
/// </exception>
147-
protected virtual ValueTask<T> TryExecuteInDbContextAsync<T>(TDbContext? context, Func<TDbContext, T> func, CancellationToken cancellationToken = default)
68+
/// <typeparam name="T">The type of the result.</typeparam>
69+
/// <param name="context">An optional existing database context.</param>
70+
/// <param name="func">The function to execute.</param>
71+
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
72+
/// <returns>A task containing the result of the operation.</returns>
73+
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <see langword="null"/>.</exception>
74+
protected ValueTask<T> ExecuteInDbContextAsync<T>(TDbContext? context, Func<TDbContext, T> func, CancellationToken cancellationToken = default)
14875
{
14976
ArgumentNullException.ThrowIfNull(func);
15077
cancellationToken.ThrowIfCancellationRequested();
78+
CheckDisposed();
15179

152-
bool contextTaken = TryCreateDbContext(ref context);
153-
try
154-
{
155-
T result = func(context);
156-
if (contextTaken)
157-
{
158-
context.Commit();
159-
}
160-
return new ValueTask<T>(result);
161-
}
162-
catch
163-
{
164-
if (contextTaken)
165-
{
166-
context.Rollback();
167-
}
168-
throw;
169-
}
170-
finally
171-
{
172-
if (contextTaken)
173-
{
174-
context.Dispose();
175-
}
176-
}
80+
return context is null ? _executor.ExecuteAsync(func, cancellationToken) : new ValueTask<T>(func(context));
17781
}
17882

17983
/// <summary>
180-
/// Asynchronously executes a function within a database context and returns a result, ensuring that the context is managed (created, committed, or rolled back) accordingly.
84+
/// Executes the specified asynchronous function using an existing database context or an owned context created by the executor.
18185
/// </summary>
182-
/// <typeparam name="T">The type of the result produced by the function.</typeparam>
183-
/// <param name="context">Optional existing context.</param>
184-
/// <param name="func">The asynchronous function to perform within the context.</param>
185-
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
186-
/// <returns>A <see cref="ValueTask{T}"/> containing the result of the asynchronous function.</returns>
187-
/// <exception cref="ArgumentNullException">
188-
/// Thrown if <paramref name="func"/> is null.
189-
/// </exception>
190-
protected virtual async ValueTask<T> TryExecuteInDbContextAsync<T>(TDbContext? context, Func<TDbContext, ValueTask<T>> func, CancellationToken cancellationToken = default)
86+
/// <typeparam name="T">The type of the result.</typeparam>
87+
/// <param name="context">An optional existing database context.</param>
88+
/// <param name="func">The asynchronous function to execute.</param>
89+
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
90+
/// <returns>A task containing the result of the asynchronous operation.</returns>
91+
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <see langword="null"/>.</exception>
92+
protected ValueTask<T> ExecuteInDbContextAsync<T>(TDbContext? context, Func<TDbContext, ValueTask<T>> func, CancellationToken cancellationToken = default)
19193
{
19294
ArgumentNullException.ThrowIfNull(func);
19395
cancellationToken.ThrowIfCancellationRequested();
96+
CheckDisposed();
19497

195-
bool contextTaken = TryCreateDbContext(ref context);
196-
try
197-
{
198-
T result = await func(context);
199-
if (contextTaken)
200-
{
201-
context.Commit();
202-
}
203-
return result;
204-
}
205-
catch
206-
{
207-
if (contextTaken)
208-
{
209-
context.Rollback();
210-
}
211-
throw;
212-
}
213-
finally
214-
{
215-
if (contextTaken)
216-
{
217-
context.Dispose();
218-
}
219-
}
98+
return context is null ? _executor.ExecuteAsync(func, cancellationToken) : func(context);
22099
}
221100

222101
#endregion
223-
}
102+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
using System.Diagnostics;
2+
3+
namespace System.Data;
4+
5+
/// <summary>
6+
/// Provides extension methods for database contexts.
7+
/// </summary>
8+
public static class DbContextExtensions
9+
{
10+
/// <summary>
11+
/// Attempts to roll back the active transaction.
12+
/// </summary>
13+
/// <param name="context">The database context.</param>
14+
/// <param name="originalException">The exception that caused the rollback attempt, if any.</param>
15+
/// <returns>
16+
/// <see langword="true"/> if the transaction was rolled back;
17+
/// otherwise, <see langword="false"/>.
18+
/// </returns>
19+
/// <exception cref="ArgumentNullException"><paramref name="context"/> is <see langword="null"/>.</exception>
20+
public static bool TryRollback(this IDbContext context, Exception? originalException = null)
21+
{
22+
ArgumentNullException.ThrowIfNull(context);
23+
24+
if (!context.IsActive)
25+
{
26+
return false;
27+
}
28+
29+
try
30+
{
31+
context.Rollback();
32+
return true;
33+
}
34+
catch (Exception rollbackException)
35+
{
36+
string message = originalException is not null
37+
? $"Database transaction rollback failed after '{originalException.GetType()}': {rollbackException}"
38+
: $"Database transaction rollback failed: {rollbackException}";
39+
40+
Trace.WriteLine(message);
41+
Debug.Fail(message);
42+
return false;
43+
}
44+
}
45+
}

‎src/System/Data/DbMigrationContext.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ protected DbMigrationContext(CancellationToken cancellationToken)
1919
/// </summary>
2020
public CancellationToken CancellationToken { get; }
2121

22+
/// <summary>
23+
/// Throws an <see cref="OperationCanceledException"/> if cancellation has been requested.
24+
/// </summary>
2225
public void ThrowIfCancellationRequested()
2326
{
2427
CancellationToken.ThrowIfCancellationRequested();

0 commit comments

Comments
 (0)