https://github.com/fgheysels/fg.dbutils
Introduces a DbSession object that manages the database connnection and transaction.
https://github.com/fgheysels/fg.dbutils
ado-net dapper dapper-extensions
Last synced: 11 months ago
JSON representation
Introduces a DbSession object that manages the database connnection and transaction.
- Host: GitHub
- URL: https://github.com/fgheysels/fg.dbutils
- Owner: fgheysels
- Created: 2020-09-13T20:24:28.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2024-03-14T16:28:23.000Z (over 2 years ago)
- Last Synced: 2024-03-15T17:02:32.216Z (over 2 years ago)
- Topics: ado-net, dapper, dapper-extensions
- Language: C#
- Homepage:
- Size: 25.4 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Fg.DbUtils
[](https://frederikgheysels.visualstudio.com/GitHub%20Pipelines/_build/latest?definitionId=7&branchName=master)
[](https://www.nuget.org/packages/fg.dbutils/)
This project introduces a `DbSession` class which manages the connection to a (relational) database and the related transaction (if any).
## Installation
```
PM > Install-Package Fg.DbUtils
```
## Usage
I'm using the `DbSession` class when using Dapper to communicate with a relational database. When starting a transaction on the `DbSession`, you do not need to pass in the `IDbTransaction` object with each database request.
Since `IDbSession` implements the `IDbConnection` interface, integration with Dapper is fairly easy.
### Executing transactional DB queries
```csharp
DbSession session = new DbSession(_connection);
await session.WithTransactionAsync( async () =>
{
// Note that we do not need to pass in the transaction parameter.
await session.ExecuteAsync("INSERT INTO Persons (FirstName, LastName) VALUES (@FirstName, @LastName)",
param: new { FirstName = "Frederik", LastName = "Gheysels" });
if( new Random().NextValue(3) % 2 != 0 )
{
// Throwing an exception will make sure that the transaction is rollbacked.
throw new InvalidOperationException();
}
// When no exception occurs, the transaction is committed
});
```
Note that `ExecuteAsync` is not a member method of `IDbSession` or `DbSession`. Instead, this is an extension method that is defined by the [Dapper micro ORM](https://github.com/DapperLib/Dapper).
This means that you can use `DbSession` as well in conjunction with Dapper to easily execute SELECT queries on your database, and Dapper will translate the resultset to your object-model:
```csharp
DbSession session = new DbSession(_connection);
IEnumerable persons = await session.QueryAsync("SELECT TOP 20 FirstName, LastName FROM Persons");
foreach( var person in persons )
{
Console.WriteLine($"Firstname = {person.FirstName} LastName = {person.LastName}");
}
```