Mtf.Database
6.0.33
dotnet add package Mtf.Database --version 6.0.33
NuGet\Install-Package Mtf.Database -Version 6.0.33
<PackageReference Include="Mtf.Database" Version="6.0.33" />
<PackageVersion Include="Mtf.Database" Version="6.0.33" />
<PackageReference Include="Mtf.Database" />
paket add Mtf.Database --version 6.0.33
#r "nuget: Mtf.Database, 6.0.33"
#:package Mtf.Database@6.0.33
#addin nuget:?package=Mtf.Database&version=6.0.33
#tool nuget:?package=Mtf.Database&version=6.0.33
Mtf.Database BaseRepository Documentation
Overview
The Mtf.Database library provides a robust, extensible data access layer based on Dapper. It features an abstract BaseRepository and a generic BaseRepository<TEntity, TIdentifierType> class designed to manage CRUD operations, automatic transactions, raw query executions, syntax validations, and structured database migrations. It supports both SQLite and SQL Server, dynamically switching providers at runtime.
Installation
To use Mtf.Database in your project:
- Add Package:
dotnet add package Mtf.Database
- Include the Namespace:
using Mtf.Database;
Class: BaseRepository
The non-generic base class handles core connection configurations, direct script executions, custom raw queries, syntax parsing, and transactional fallbacks.
Static and Instance Properties
| Property | Type | Scope | Description |
|---|---|---|---|
ConnectionString |
string |
Instance | The database connection string (init-only). |
CommandTimeout |
int? |
Static | Optional global command timeout setting in seconds. |
DbProvider |
DbProviderType |
Static | Specifies the active engine (SQLite or SqlServer). Default is SqlServer. |
ScriptsToExecute |
List<string> |
Static | Pre-registered database script names intended for migrations. |
DatabaseScriptsAssembly |
Assembly? |
Static | Assembly containing embedded SQL script resources. |
DatabaseScriptsLocation |
string? |
Static | Root namespace path to embedded SQL scripts. |
Key Methods
Migration Management
static void ExecuteMigrations(string connectionString)Iterates throughScriptsToExecute, fetches script contents viaScriptCache, and applies them inside a single database transaction. Rollback occurs automatically on failure, throwing aSqlScriptExecutionException.
Synchronous & Asynchronous Script Execution
void Execute(string scriptName, object? param = null)Executes an embedded SQL script wrapped in an isolated transaction.Task ExecuteAsync(string scriptName, object? param = null)Asynchronous variant ofExecuteusing structural async transaction handlers.void ExecuteWithoutTransaction(string scriptName, object? param = null)Runs a script outside of an active database transaction block.void Execute(params SqlParam[] parameters)Batch executes multipleSqlParamentries sequentially within a single unified transaction.
Raw Queries and Metrics
DataTable ExecuteQuery(string query, Dictionary<string, object>? parameters = null)Executes a raw SQL statement, passing structured query parameters safely. Returns a standardDataTable. Throws anArgumentExceptionif the input text contains potentially destructive keywords.string? ExecuteScalarQuery(string query)Quickly evaluates a query and returns its scalar output as a string.int GetDatabaseUsagePercentageWithLimit()(SQL Server exclusive) Returns the total storage consumption percentage relative to engine limits (e.g., managing the 10GB boundary in Express editions).
SQL Parsing and Validation
bool HasValidSqlSyntax(string sql, bool checkDeclarations, out Exception? exception)Validates standard database script structures. Internally leveragesSET PARSEONLY ONacross processing batches without physical script commitment.
Class: BaseRepository<TEntity, TIdentifierType>
An abstract generic repository enforcing strongly-typed lifecycle workflows for internal business entities.
public abstract class BaseRepository<TEntity, TIdentifierType> : BaseRepository
where TEntity : class, IHasIdentifier<TIdentifierType>
Script Naming Convention
The repository automatically resolves operational script pathways at instantiation. It expects scripts to reside inside an embedded directory mirroring the structural layout: {ScriptsSubfolderName}.{Operation}{EntityName} (e.g., Server.SelectServer).
Contextual Operations
Custom Target Transactions
TEntity ExecuteInTransaction(Func<DbConnection, IDbTransaction, TEntity> operation)Encapsulates explicit operations inside custom processing scopes returning unified state elements.void ExecuteInTransaction(Action<DbConnection, IDbTransaction> operation)Encapsulates structural non-query operations inside structured workflows.
Direct Queries & Stored Procedures
ReadOnlyCollection<TEntity> Query(string scriptName, object param)/QueryAsync(...)Fetches relational datasets translated into read-only structural collections.TEntity? QuerySingleOrDefault(string scriptName, object? param = null)Returns a unique domain record matching arguments or falls back tonull.ReadOnlyCollection<TEntity> ExecuteStoredProcedure(string procedureName, object? param = null)Invokes concrete procedural components returning mapped entities.
Native CRUD Operations
| Method | Return Type | Strategy |
|---|---|---|
Select(TIdentifierType id) |
TEntity? |
Synch Lookup |
SelectAll() |
ReadOnlyCollection<TEntity> |
Complete Fetch |
SelectWhere(object param) |
ReadOnlyCollection<TEntity> |
Conditional Query |
Insert(TEntity? model) |
void |
Standard Persistence |
InsertAndReturnId<T>(TEntity model) |
T (struct) |
Evaluates context via SCOPE_IDENTITY() |
Update(TEntity? model) |
void |
Structural Modification |
Delete(TIdentifierType id) |
void |
Unique Record Erasure |
DeleteWhere(object? param) |
void |
Conditional Mass Erasure |
Asynchronous Lifecycle Equivalents
Task<ReadOnlyCollection<TEntity>> GetAllAsync()Task<ReadOnlyCollection<TEntity>> GetAllWhereAsync(object param)Task<TEntity?> GetByIdAsync(TIdentifierType id)Task<TEntity?> InsertAsync(TEntity entity)(Persists and returns the freshly loaded record)Task<TEntity?> UpdateAsync(TEntity entity)(Updates and returns the current database state)Task DeleteAsync(TIdentifierType id)
Example Usage
using Mtf.Database;
using Mtf.Database.Enums;
using System;
using System.Threading.Tasks;
public class ServerEntity : IHasIdentifier<int>
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Location { get; set; } = string.Empty;
}
public class ServerRepository : BaseRepository<ServerEntity, int>
{
public ServerRepository(string connectionString) : base(connectionString) { }
}
public class Program
{
public static async Task Main()
{
// 1. Global Setup Configuration
BaseRepository.DbProvider = DbProviderType.SqlServer;
BaseRepository.DatabaseScriptsAssembly = typeof(Program).Assembly;
BaseRepository.DatabaseScriptsLocation = "YourApp.Database.Scripts";
BaseRepository.CommandTimeout = 45;
// Register Migrations
BaseRepository.ScriptsToExecute.Add("Migration_v1_CreateTables");
string connString = "Server=localhost;Database=LiveDB;Trusted_Connection=True;TrustServerCertificate=True;";
// Run Database migrations
BaseRepository.ExecuteMigrations(connString);
// 2. Initialize instance repository
var repo = new ServerRepository(connString);
// 3. Perform Operations Asynchronously
var newServer = new ServerEntity { Name = "Node-Alpha", Location = "Budapest" };
ServerEntity? savedServer = await repo.InsertAsync(newServer);
if (savedServer != null)
{
Console.WriteLine($"Successfully saved entity with ID: {savedServer.Id}");
}
// 4. Fetch structural lists conditionally
var localServers = await repo.GetAllWhereAsync(new { Location = "Budapest" });
foreach (var server in localServers)
{
Console.WriteLine($"Active Node: {server.Name}");
}
}
}
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Dapper (>= 2.1.79)
- Microsoft.Data.SqlClient (>= 7.0.2)
- Microsoft.Data.Sqlite.Core (>= 10.0.9)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Mtf.Database:
| Package | Downloads |
|---|---|
|
Mtf.Web
The `Mtf.Web.WebAPI` layer provides a generic, base implementation for ASP.NET Core controllers and DTO/model conversion. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 6.0.33 | 92 | 7/17/2026 |
| 6.0.31 | 97 | 7/11/2026 |
| 5.0.30 | 98 | 7/11/2026 |
| 5.0.24 | 104 | 7/11/2026 |
| 5.0.23 | 92 | 7/7/2026 |
| 5.0.15 | 104 | 7/5/2026 |
| 4.0.4 | 100 | 7/2/2026 |
| 3.0.2 | 103 | 6/30/2026 |
| 3.0.1 | 101 | 6/19/2026 |
| 2.0.80 | 258 | 9/3/2025 |
| 2.0.66 | 298 | 7/26/2025 |
| 2.0.65 | 626 | 7/24/2025 |
| 2.0.62 | 201 | 6/6/2025 |
| 2.0.60 | 214 | 5/26/2025 |
| 2.0.59 | 201 | 5/22/2025 |
| 2.0.44 | 231 | 5/20/2025 |
| 2.0.43 | 226 | 5/20/2025 |
| 2.0.40 | 258 | 5/20/2025 |
| 2.0.39 | 262 | 5/8/2025 |
| 2.0.38 | 218 | 4/29/2025 |