Migrate UserManagement to a vertical slice (Features.UserManagement)

Same pattern as the Breweries migration: Service.UserManagement and the
UserAccount repository fold into Features.UserManagement, with MediatR
queries replacing UserService. UpdateUserCommand/Handler carry forward
IUserService.UpdateAsync as-is (it has no HTTP route today, and adding one
is a separate decision from this migration). Adds handler/repository test
coverage that didn't exist before, since Service.UserManagement had no
test project.
This commit is contained in:
Aaron Po
2026-06-20 00:02:27 -04:00
parent 34ba7e8271
commit 5cf4df1fd8
24 changed files with 267 additions and 118 deletions

View File

@@ -0,0 +1,22 @@
using Domain.Entities;
using Features.UserManagement.Commands.UpdateUser;
using Features.UserManagement.Repository;
using Moq;
namespace Features.UserManagement.Tests.Commands;
public class UpdateUserHandlerTests
{
[Fact]
public async Task Handle_DelegatesToRepository()
{
var repoMock = new Mock<IUserAccountRepository>();
var handler = new UpdateUserHandler(repoMock.Object);
var user = new UserAccount { UserAccountId = Guid.NewGuid() };
repoMock.Setup(r => r.UpdateAsync(user)).Returns(Task.CompletedTask);
await handler.Handle(new UpdateUserCommand(user), CancellationToken.None);
repoMock.Verify(r => r.UpdateAsync(user), Times.Once);
}
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<RootNamespace>Features.UserManagement.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="FluentAssertions" Version="6.9.0" />
<PackageReference Include="DbMocker" Version="1.26.0" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Features.UserManagement\Features.UserManagement.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,23 @@
using Domain.Entities;
using FluentAssertions;
using Features.UserManagement.Queries.GetAllUsers;
using Features.UserManagement.Repository;
using Moq;
namespace Features.UserManagement.Tests.Queries;
public class GetAllUsersHandlerTests
{
[Fact]
public async Task Handle_PassesLimitAndOffset_ToRepository()
{
var repoMock = new Mock<IUserAccountRepository>();
var handler = new GetAllUsersHandler(repoMock.Object);
repoMock.Setup(r => r.GetAllAsync(10, 5)).ReturnsAsync(Array.Empty<UserAccount>());
var result = await handler.Handle(new GetAllUsersQuery(10, 5), CancellationToken.None);
result.Should().BeEmpty();
repoMock.Verify(r => r.GetAllAsync(10, 5), Times.Once);
}
}

View File

@@ -0,0 +1,41 @@
using Domain.Entities;
using Domain.Exceptions;
using FluentAssertions;
using Features.UserManagement.Queries.GetUserById;
using Features.UserManagement.Repository;
using Moq;
namespace Features.UserManagement.Tests.Queries;
public class GetUserByIdHandlerTests
{
private readonly Mock<IUserAccountRepository> _repoMock = new();
private readonly GetUserByIdHandler _handler;
public GetUserByIdHandlerTests()
{
_handler = new GetUserByIdHandler(_repoMock.Object);
}
[Fact]
public async Task Handle_ReturnsUser_WhenFound()
{
var user = new UserAccount { UserAccountId = Guid.NewGuid(), Username = "test" };
_repoMock.Setup(r => r.GetByIdAsync(user.UserAccountId)).ReturnsAsync(user);
var result = await _handler.Handle(new GetUserByIdQuery(user.UserAccountId), CancellationToken.None);
result.Should().Be(user);
}
[Fact]
public async Task Handle_Throws_WhenNotFound()
{
var id = Guid.NewGuid();
_repoMock.Setup(r => r.GetByIdAsync(id)).ReturnsAsync((UserAccount?)null);
var act = async () => await _handler.Handle(new GetUserByIdQuery(id), CancellationToken.None);
await act.Should().ThrowAsync<NotFoundException>();
}
}

View File

@@ -0,0 +1,11 @@
using System.Data.Common;
using Infrastructure.Sql;
namespace Features.UserManagement.Tests.Repository;
internal class TestConnectionFactory(DbConnection conn) : ISqlConnectionFactory
{
private readonly DbConnection _conn = conn;
public DbConnection CreateConnection() => _conn;
}

View File

@@ -0,0 +1,179 @@
using Apps72.Dev.Data.DbMocker;
using FluentAssertions;
using Features.UserManagement.Repository;
namespace Features.UserManagement.Tests.Repository;
public class UserAccountRepositoryTests
{
private static UserAccountRepository CreateRepo(MockDbConnection conn) =>
new(new TestConnectionFactory(conn));
[Fact]
public async Task GetByIdAsync_ReturnsRow_Mapped()
{
var conn = new MockDbConnection();
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountById")
.ReturnsTable(
MockTable
.WithColumns(
("UserAccountId", typeof(Guid)),
("Username", typeof(string)),
("FirstName", typeof(string)),
("LastName", typeof(string)),
("Email", typeof(string)),
("CreatedAt", typeof(DateTime)),
("UpdatedAt", typeof(DateTime?)),
("DateOfBirth", typeof(DateTime)),
("Timer", typeof(byte[]))
)
.AddRow(
Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
"yerb",
"Aaron",
"Po",
"aaronpo@example.com",
new DateTime(2020, 1, 1),
null,
new DateTime(1990, 1, 1),
null
)
);
var repo = CreateRepo(conn);
var result = await repo.GetByIdAsync(
Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
);
result.Should().NotBeNull();
result!.Username.Should().Be("yerb");
result.Email.Should().Be("aaronpo@example.com");
}
[Fact]
public async Task GetAllAsync_ReturnsMultipleRows()
{
var conn = new MockDbConnection();
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetAllUserAccounts")
.ReturnsTable(
MockTable
.WithColumns(
("UserAccountId", typeof(Guid)),
("Username", typeof(string)),
("FirstName", typeof(string)),
("LastName", typeof(string)),
("Email", typeof(string)),
("CreatedAt", typeof(DateTime)),
("UpdatedAt", typeof(DateTime?)),
("DateOfBirth", typeof(DateTime)),
("Timer", typeof(byte[]))
)
.AddRow(
Guid.NewGuid(),
"a",
"A",
"A",
"a@example.com",
DateTime.UtcNow,
null,
DateTime.UtcNow.Date,
null
)
.AddRow(
Guid.NewGuid(),
"b",
"B",
"B",
"b@example.com",
DateTime.UtcNow,
null,
DateTime.UtcNow.Date,
null
)
);
var repo = CreateRepo(conn);
var results = (await repo.GetAllAsync(null, null)).ToList();
results.Should().HaveCount(2);
results
.Select(r => r.Username)
.Should()
.BeEquivalentTo(new[] { "a", "b" });
}
[Fact]
public async Task GetByUsername_ReturnsRow()
{
var conn = new MockDbConnection();
conn.Mocks.When(cmd =>
cmd.CommandText == "usp_GetUserAccountByUsername"
)
.ReturnsTable(
MockTable
.WithColumns(
("UserAccountId", typeof(Guid)),
("Username", typeof(string)),
("FirstName", typeof(string)),
("LastName", typeof(string)),
("Email", typeof(string)),
("CreatedAt", typeof(DateTime)),
("UpdatedAt", typeof(DateTime?)),
("DateOfBirth", typeof(DateTime)),
("Timer", typeof(byte[]))
)
.AddRow(
Guid.NewGuid(),
"lookupuser",
"L",
"U",
"lookup@example.com",
DateTime.UtcNow,
null,
DateTime.UtcNow.Date,
null
)
);
var repo = CreateRepo(conn);
var result = await repo.GetByUsernameAsync("lookupuser");
result.Should().NotBeNull();
result!.Email.Should().Be("lookup@example.com");
}
[Fact]
public async Task GetByEmail_ReturnsRow()
{
var conn = new MockDbConnection();
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountByEmail")
.ReturnsTable(
MockTable
.WithColumns(
("UserAccountId", typeof(Guid)),
("Username", typeof(string)),
("FirstName", typeof(string)),
("LastName", typeof(string)),
("Email", typeof(string)),
("CreatedAt", typeof(DateTime)),
("UpdatedAt", typeof(DateTime?)),
("DateOfBirth", typeof(DateTime)),
("Timer", typeof(byte[]))
)
.AddRow(
Guid.NewGuid(),
"byemail",
"B",
"E",
"byemail@example.com",
DateTime.UtcNow,
null,
DateTime.UtcNow.Date,
null
)
);
var repo = CreateRepo(conn);
var result = await repo.GetByEmailAsync("byemail@example.com");
result.Should().NotBeNull();
result!.Username.Should().Be("byemail");
}
}

View File

@@ -0,0 +1,10 @@
using Domain.Entities;
using MediatR;
namespace Features.UserManagement.Commands.UpdateUser;
/// <summary>
/// Updates an existing user account. Not currently exposed via any HTTP route, carried forward
/// from <c>IUserService.UpdateAsync</c> as-is.
/// </summary>
public record UpdateUserCommand(UserAccount UserAccount) : IRequest;

View File

@@ -0,0 +1,15 @@
using Features.UserManagement.Repository;
using MediatR;
namespace Features.UserManagement.Commands.UpdateUser;
/// <summary>
/// Handles <see cref="UpdateUserCommand"/> by persisting changes to an existing user account.
/// </summary>
/// <param name="repository">Repository used to persist the updated user account.</param>
public class UpdateUserHandler(IUserAccountRepository repository)
: IRequestHandler<UpdateUserCommand>
{
public Task Handle(UpdateUserCommand request, CancellationToken cancellationToken) =>
repository.UpdateAsync(request.UserAccount);
}

View File

@@ -0,0 +1,45 @@
using Domain.Entities;
using Features.UserManagement.Queries.GetAllUsers;
using Features.UserManagement.Queries.GetUserById;
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace Features.UserManagement.Controllers
{
/// <summary>
/// Provides read-only endpoints for retrieving user accounts.
/// </summary>
/// <param name="mediator">Used to dispatch user queries to their handlers.</param>
[ApiController]
[Route("api/[controller]")]
public class UserController(IMediator mediator) : ControllerBase
{
/// <summary>
/// Retrieves a paginated list of user accounts.
/// </summary>
/// <param name="limit">The maximum number of user accounts to return, or <c>null</c> for no limit.</param>
/// <param name="offset">The number of user accounts to skip before returning results, or <c>null</c> for no offset.</param>
/// <returns>A <c>200 OK</c> result containing the collection of <see cref="UserAccount"/> entities.</returns>
[HttpGet]
public async Task<ActionResult<IEnumerable<UserAccount>>> GetAll(
[FromQuery] int? limit,
[FromQuery] int? offset
)
{
var users = await mediator.Send(new GetAllUsersQuery(limit, offset));
return Ok(users);
}
/// <summary>
/// Retrieves a single user account by its unique identifier.
/// </summary>
/// <param name="id">The unique identifier of the user account to retrieve.</param>
/// <returns>A <c>200 OK</c> result containing the matching <see cref="UserAccount"/>.</returns>
[HttpGet("{id:guid}")]
public async Task<ActionResult<UserAccount>> GetById(Guid id)
{
var user = await mediator.Send(new GetUserByIdQuery(id));
return Ok(user);
}
}
}

View File

@@ -0,0 +1,16 @@
using Features.UserManagement.Repository;
using Microsoft.Extensions.DependencyInjection;
namespace Features.UserManagement.DependencyInjection;
/// <summary>
/// Registers the services owned by the UserManagement feature slice.
/// </summary>
public static class FeaturesUserManagementServiceCollectionExtensions
{
public static IServiceCollection AddFeaturesUserManagement(this IServiceCollection services)
{
services.AddScoped<IUserAccountRepository, UserAccountRepository>();
return services;
}
}

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Features.UserManagement</RootNamespace>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Domain\Domain.Entities\Domain.Entities.csproj" />
<ProjectReference Include="..\..\Domain\Domain.Exceptions\Domain.Exceptions.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Sql\Infrastructure.Sql.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Application\Shared.Application.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,16 @@
using Domain.Entities;
using Features.UserManagement.Repository;
using MediatR;
namespace Features.UserManagement.Queries.GetAllUsers;
/// <summary>
/// Handles <see cref="GetAllUsersQuery"/> by retrieving a paginated list of user accounts.
/// </summary>
/// <param name="repository">Repository used to query user account data.</param>
public class GetAllUsersHandler(IUserAccountRepository repository)
: IRequestHandler<GetAllUsersQuery, IEnumerable<UserAccount>>
{
public Task<IEnumerable<UserAccount>> Handle(GetAllUsersQuery request, CancellationToken cancellationToken) =>
repository.GetAllAsync(request.Limit, request.Offset);
}

View File

@@ -0,0 +1,9 @@
using Domain.Entities;
using MediatR;
namespace Features.UserManagement.Queries.GetAllUsers;
/// <summary>
/// Retrieves a paginated list of user accounts.
/// </summary>
public record GetAllUsersQuery(int? Limit, int? Offset) : IRequest<IEnumerable<UserAccount>>;

View File

@@ -0,0 +1,23 @@
using Domain.Entities;
using Domain.Exceptions;
using Features.UserManagement.Repository;
using MediatR;
namespace Features.UserManagement.Queries.GetUserById;
/// <summary>
/// Handles <see cref="GetUserByIdQuery"/> by looking up the matching user account.
/// </summary>
/// <param name="repository">Repository used to query user account data.</param>
public class GetUserByIdHandler(IUserAccountRepository repository)
: IRequestHandler<GetUserByIdQuery, UserAccount>
{
/// <exception cref="NotFoundException">Thrown when no user account exists with the given ID.</exception>
public async Task<UserAccount> Handle(GetUserByIdQuery request, CancellationToken cancellationToken)
{
var user = await repository.GetByIdAsync(request.UserAccountId);
if (user is null)
throw new NotFoundException($"User with ID {request.UserAccountId} not found");
return user;
}
}

View File

@@ -0,0 +1,9 @@
using Domain.Entities;
using MediatR;
namespace Features.UserManagement.Queries.GetUserById;
/// <summary>
/// Retrieves a single user account by its unique identifier.
/// </summary>
public record GetUserByIdQuery(Guid UserAccountId) : IRequest<UserAccount>;

View File

@@ -0,0 +1,51 @@
namespace Features.UserManagement.Repository;
/// <summary>
/// Repository for CRUD operations on user account records.
/// </summary>
public interface IUserAccountRepository
{
/// <summary>
/// Retrieves a user account by its unique identifier.
/// </summary>
/// <param name="id">The unique identifier of the user account.</param>
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
Task<Domain.Entities.UserAccount?> GetByIdAsync(Guid id);
/// <summary>
/// Retrieves all user accounts, optionally paginated.
/// </summary>
/// <param name="limit">The maximum number of records to return, or <c>null</c> for no limit.</param>
/// <param name="offset">The number of records to skip, or <c>null</c> for no offset.</param>
/// <returns>The collection of matching <see cref="Domain.Entities.UserAccount"/> records.</returns>
Task<IEnumerable<Domain.Entities.UserAccount>> GetAllAsync(
int? limit,
int? offset
);
/// <summary>
/// Updates an existing user account's details.
/// </summary>
/// <param name="userAccount">The user account containing updated values. Must have a valid <c>UserAccountId</c>.</param>
Task UpdateAsync(Domain.Entities.UserAccount userAccount);
/// <summary>
/// Deletes a user account by its unique identifier.
/// </summary>
/// <param name="id">The unique identifier of the user account to delete.</param>
Task DeleteAsync(Guid id);
/// <summary>
/// Retrieves a user account by username.
/// </summary>
/// <param name="username">The username to search for.</param>
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
Task<Domain.Entities.UserAccount?> GetByUsernameAsync(string username);
/// <summary>
/// Retrieves a user account by email address.
/// </summary>
/// <param name="email">The email address to search for.</param>
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
Task<Domain.Entities.UserAccount?> GetByEmailAsync(string email);
}

View File

@@ -0,0 +1,197 @@
using System.Data;
using System.Data.Common;
using Infrastructure.Sql;
namespace Features.UserManagement.Repository;
/// <summary>
/// ADO.NET-based implementation of <see cref="IUserAccountRepository"/> backed by SQL Server
/// stored procedures.
/// </summary>
/// <param name="connectionFactory">The factory used to create database connections.</param>
public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
: Infrastructure.Sql.Repository<Domain.Entities.UserAccount>(connectionFactory),
IUserAccountRepository
{
/// <summary>
/// Retrieves a user account by ID using the <c>usp_GetUserAccountById</c> stored procedure.
/// </summary>
/// <param name="id">The unique identifier of the user account.</param>
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
public async Task<Domain.Entities.UserAccount?> GetByIdAsync(Guid id)
{
await using var connection = await CreateConnection();
await using var command = connection.CreateCommand();
command.CommandText = "usp_GetUserAccountById";
command.CommandType = CommandType.StoredProcedure;
AddParameter(command, "@UserAccountId", id);
await using var reader = await command.ExecuteReaderAsync();
return await reader.ReadAsync() ? MapToEntity(reader) : null;
}
/// <summary>
/// Retrieves all user accounts, optionally paginated, using the <c>usp_GetAllUserAccounts</c>
/// stored procedure. The <c>@Limit</c> and <c>@Offset</c> parameters are only added when their
/// corresponding argument has a value.
/// </summary>
/// <param name="limit">The maximum number of records to return, or <c>null</c> for no limit.</param>
/// <param name="offset">The number of records to skip, or <c>null</c> for no offset.</param>
/// <returns>The collection of matching <see cref="Domain.Entities.UserAccount"/> records.</returns>
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
public async Task<IEnumerable<Domain.Entities.UserAccount>> GetAllAsync(
int? limit,
int? offset
)
{
await using var connection = await CreateConnection();
await using var command = connection.CreateCommand();
command.CommandText = "usp_GetAllUserAccounts";
command.CommandType = CommandType.StoredProcedure;
if (limit.HasValue)
AddParameter(command, "@Limit", limit.Value);
if (offset.HasValue)
AddParameter(command, "@Offset", offset.Value);
await using var reader = await command.ExecuteReaderAsync();
var users = new List<Domain.Entities.UserAccount>();
while (await reader.ReadAsync())
{
users.Add(MapToEntity(reader));
}
return users;
}
/// <summary>
/// Updates a user account's username, first name, last name, email, and date of birth using
/// the <c>usp_UpdateUserAccount</c> stored procedure.
/// </summary>
/// <param name="userAccount">The user account containing updated values. Must have a valid <c>UserAccountId</c>.</param>
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
public async Task UpdateAsync(Domain.Entities.UserAccount userAccount)
{
await using var connection = await CreateConnection();
await using var command = connection.CreateCommand();
command.CommandText = "usp_UpdateUserAccount";
command.CommandType = CommandType.StoredProcedure;
AddParameter(command, "@UserAccountId", userAccount.UserAccountId);
AddParameter(command, "@Username", userAccount.Username);
AddParameter(command, "@FirstName", userAccount.FirstName);
AddParameter(command, "@LastName", userAccount.LastName);
AddParameter(command, "@Email", userAccount.Email);
AddParameter(command, "@DateOfBirth", userAccount.DateOfBirth);
await command.ExecuteNonQueryAsync();
}
/// <summary>
/// Deletes a user account by ID using the <c>usp_DeleteUserAccount</c> stored procedure.
/// </summary>
/// <param name="id">The unique identifier of the user account to delete.</param>
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
public async Task DeleteAsync(Guid id)
{
await using var connection = await CreateConnection();
await using var command = connection.CreateCommand();
command.CommandText = "usp_DeleteUserAccount";
command.CommandType = CommandType.StoredProcedure;
AddParameter(command, "@UserAccountId", id);
await command.ExecuteNonQueryAsync();
}
/// <summary>
/// Retrieves a user account by username using the <c>usp_GetUserAccountByUsername</c> stored procedure.
/// </summary>
/// <param name="username">The username to search for.</param>
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
public async Task<Domain.Entities.UserAccount?> GetByUsernameAsync(
string username
)
{
await using var connection = await CreateConnection();
await using var command = connection.CreateCommand();
command.CommandText = "usp_GetUserAccountByUsername";
command.CommandType = CommandType.StoredProcedure;
AddParameter(command, "@Username", username);
await using var reader = await command.ExecuteReaderAsync();
return await reader.ReadAsync() ? MapToEntity(reader) : null;
}
/// <summary>
/// Retrieves a user account by email address using the <c>usp_GetUserAccountByEmail</c> stored procedure.
/// </summary>
/// <param name="email">The email address to search for.</param>
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
public async Task<Domain.Entities.UserAccount?> GetByEmailAsync(
string email
)
{
await using var connection = await CreateConnection();
await using var command = connection.CreateCommand();
command.CommandText = "usp_GetUserAccountByEmail";
command.CommandType = CommandType.StoredProcedure;
AddParameter(command, "@Email", email);
await using var reader = await command.ExecuteReaderAsync();
return await reader.ReadAsync() ? MapToEntity(reader) : null;
}
/// <summary>
/// Maps the current row of a data reader to a <see cref="Domain.Entities.UserAccount"/> entity.
/// </summary>
/// <param name="reader">The data reader positioned on the row to map.</param>
/// <returns>The mapped <see cref="Domain.Entities.UserAccount"/> instance.</returns>
protected override Domain.Entities.UserAccount MapToEntity(
DbDataReader reader
)
{
return new Domain.Entities.UserAccount
{
UserAccountId = reader.GetGuid(reader.GetOrdinal("UserAccountId")),
Username = reader.GetString(reader.GetOrdinal("Username")),
FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
LastName = reader.GetString(reader.GetOrdinal("LastName")),
Email = reader.GetString(reader.GetOrdinal("Email")),
CreatedAt = reader.GetDateTime(reader.GetOrdinal("CreatedAt")),
UpdatedAt = reader.IsDBNull(reader.GetOrdinal("UpdatedAt"))
? null
: reader.GetDateTime(reader.GetOrdinal("UpdatedAt")),
DateOfBirth = reader.GetDateTime(reader.GetOrdinal("DateOfBirth")),
Timer = reader.IsDBNull(reader.GetOrdinal("Timer"))
? null
: (byte[])reader["Timer"],
};
}
/// <summary>
/// Helper method to add a parameter to a database command, converting <c>null</c> values to
/// <see cref="DBNull.Value"/>.
/// </summary>
/// <param name="command">The command to add the parameter to.</param>
/// <param name="name">The parameter name (including any prefix, e.g. "@Username").</param>
/// <param name="value">The parameter value, or <c>null</c> to bind <see cref="DBNull.Value"/>.</param>
private static void AddParameter(
DbCommand command,
string name,
object? value
)
{
var p = command.CreateParameter();
p.ParameterName = name;
p.Value = value ?? DBNull.Value;
command.Parameters.Add(p);
}
}