Getting Started with EricksonLopez.Transaction
Install the published 2.0.0 packages (EricksonLopez.Transaction, .PostgreSql, .Result, and .Dapper) from NuGet.
dotnet add package EricksonLopez.Transaction --version 2.0.0<PackageReference Include="EricksonLopez.Transaction" Version="2.0.0" /><PackageVersion Include="EricksonLopez.Transaction" Version="2.0.0" />dotnet add package EricksonLopez.Transaction.PostgreSql --version 2.0.0dotnet add package EricksonLopez.Transaction.Result --version 2.0.0dotnet add package EricksonLopez.Transaction.Dapper --version 2.0.0Publication Note:
EricksonLopez.Transaction.EntityFrameworkCore,.Mediator,.Resilience, and.Analyzersare unpublished local workspace packages (3.1.0) — do not reference them from NuGet.org.
Quick Start: ExecuteResultAsync with PostgreSQL & Dapper
Section titled “Quick Start: ExecuteResultAsync with PostgreSQL & Dapper”AddPostgreSqlTransaction resides in namespace Microsoft.Extensions.DependencyInjection;:
using System;using System.Threading;using System.Threading.Tasks;using EricksonLopez.Result;using EricksonLopez.Transaction;using EricksonLopez.Transaction.Dapper;using EricksonLopez.Transaction.Result;using Microsoft.Extensions.DependencyInjection;
namespace Example.TransactionQuickStart;
public static class OrderTransferService{ public static void Register(IServiceCollection services, string connectionString) { services.AddPostgreSqlTransaction(connectionString); }
public static Task<Result<int>> DebitAccountAsync( ITransactionManager txManager, Guid accountId, decimal amount, CancellationToken ct) { return txManager.ExecuteResultAsync(async ctx => { if (amount <= 0m) { return Result<int>.Failure( Error.Validation("Account.InvalidAmount", "Debit amount must be positive.")); }
int rows = await ctx.ExecuteAsync( "UPDATE accounts SET balance = balance - @Amount WHERE id = @AccountId", new { AccountId = accountId, Amount = amount }, cancellationToken: ct);
return rows == 1 ? Result<int>.Success(rows) : Result<int>.Failure(Error.NotFound("Account.NotFound", "Account was not found.")); }, TransactionOptions.Default, ct); }}