Refactors the book slice across the stack

This commit is contained in:
BinaryAlley committed 2026-09-19 12:56:46 -07:00
1 parent 54cae054c1
commit c112c64c25
8 files changed
+272 -38

No files matched your search

@@ -71,8 +71,9 @@ public static class BookMapping
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()],
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null,
UpdatedBy = domainEntity.UpdatedOnUtc.HasValue ? Guid.NewGuid() : null,
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null,
};
}
@@ -34,12 +34,12 @@ public static class UpdateBookCommandMapping
public static Result<Book> ToDomainEntity(this UpdateBookCommand command, BookEntity existingBook)
{
IEnumerable<Result<BookRating>> domainRatingsResult = command.Ratings!.ToDomainEntities();
List<Error> errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors) ?? []];
List<Error> errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)];
if (errors.Count > 0)
return errors;
IEnumerable<Result<Isbn>> domainIsbnsResult = command.ISBNs!.ToDomainEntities();
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors) ?? []];
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)];
if (errors.Count > 0)
return errors;
@@ -57,7 +57,7 @@ public static class UpdateBookCommandMapping
// Map the media contributors referenced by the user to their domain counterparts; a contributor is identified by its id and carries the role it played.
IEnumerable<Result<BookMediaContributor>> domainContributorsResult = command.Contributors!.ToBookDomainEntities();
errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors) ?? []];
errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors)];
if (errors.Count > 0)
return errors;
@@ -30,12 +30,12 @@ public static class WrittenContentMetadataDtoMapping
return domainReleaseInfoResult.Value.Errors;
IEnumerable<Result<Genre>> domainGenresResult = dto.Genres!.ToDomainEntities();
List<Error> errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors) ?? []];
List<Error> errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)];
if (errors.Count > 0)
return errors;
IEnumerable<Result<Tag>> domainTagsResult = dto.Tags!.ToDomainEntities();
errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors) ?? []];
errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)];
if (errors.Count > 0)
return errors;
@@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Specifications;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
@@ -100,7 +101,8 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.Contributors)
.Include(book => book.Artwork);
.Include(book => book.Artwork)
.AsSplitQuery();
}
return await query.FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false);
}
@@ -130,7 +132,8 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.Contributors)
.Include(book => book.Artwork);
.Include(book => book.Artwork)
.AsSplitQuery();
}
// Books should always be retrieved only per owning libraries.
@@ -283,6 +286,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.ISBNs)
.Include(book => book.Contributors)
.Include(book => book.Artwork)
.AsSplitQuery()
.Where(book => book.LibraryId == libraryId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
@@ -301,6 +305,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Artwork)
.AsSplitQuery()
.FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false);
}
@@ -320,6 +325,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Contributors)
.AsSplitQuery()
.Where(book => book.LibraryId == libraryId
&& book.MetadataStatus != MetadataStatus.Enriched
&& (lastPath == null || book.Path.CompareTo(lastPath) > 0))
@@ -356,6 +362,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Artwork)
.AsSplitQuery()
.Where(book => book.LibraryId == libraryId
&& !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched)
&& (lastPath == null || book.Path.CompareTo(lastPath) > 0))
@@ -483,7 +490,7 @@ internal sealed class BookRepository : IBookRepository
}
/// <summary>
/// Updates a book, replacing its editable data while preserving its identity, enrichment and audit columns.
/// Updates a book, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, its enrichment columns and its audit columns.
/// </summary>
/// <param name="data">The book whose editable data is applied to the stored book.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -500,49 +507,90 @@ internal sealed class BookRepository : IBookRepository
if (foundBook is null)
return Errors.WrittenContent.BookNotFound;
// The stored enrichment and identity columns are never overwritten by an edit: they are owned by the scan and by the record itself.
// The stored enrichment and identity columns are never overwritten by an edit: they are owned by the scan and by the record itself. The audit columns are
// only ever written by the auditing interceptor, which is why the copier restores them after copying the editable values.
Guid libraryId = foundBook.LibraryId;
string path = foundBook.Path;
MetadataStatus metadataStatus = foundBook.MetadataStatus;
DateTime? lastMetadataUpdateUtc = foundBook.LastMetadataUpdateUtc;
string? metadataProvider = foundBook.MetadataProvider;
DateTime createdOnUtc = foundBook.CreatedOnUtc;
Guid createdBy = foundBook.CreatedBy;
// Copy the editable scalar properties of the book, ignoring the unchanged collection and enrichment columns.
_luminaDbContext.Entry(foundBook).CurrentValues.SetValues(data);
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundBook, data);
foundBook.LibraryId = libraryId;
foundBook.Path = path;
foundBook.MetadataStatus = metadataStatus;
foundBook.LastMetadataUpdateUtc = lastMetadataUpdateUtc;
foundBook.MetadataProvider = metadataProvider;
foundBook.CreatedOnUtc = createdOnUtc;
foundBook.CreatedBy = createdBy;
// Reuse the stored tags and genres whose names already exist, so that the shared tables are not duplicated.
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(tag => data.Tags.Select(bookTag => bookTag.Name).Contains(tag.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => data.Genres.Select(bookGenre => bookGenre.Name).Contains(genre.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
await ReconcileTagsAndGenresAsync(foundBook, data, cancellationToken).ConfigureAwait(false);
foundBook.Tags.Clear();
foundBook.Tags.UnionWith(data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag));
foundBook.Genres.Clear();
foundBook.Genres.UnionWith(data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre));
// ISBNs are owned value objects with no identity anyone could reference, so an ISBN whose format changed is replaced as a whole, while the ones that did not
// change are left exactly as they are stored. Matching by the ISBN value keeps an update in place instead of recreating every ISBN of the book.
CollectionReconciler.Reconcile(
foundBook.ISBNs,
data.ISBNs,
existingIsbn => existingIsbn.Value ?? string.Empty,
incomingIsbn => incomingIsbn.Value ?? string.Empty,
shouldReplace: (existingIsbn, incomingIsbn) => !existingIsbn.Equals(incomingIsbn),
createNew: incomingIsbn => incomingIsbn);
// Replace the owned collections of the book, so that removed entries are deleted and new entries are inserted.
foundBook.ISBNs.Clear();
foundBook.ISBNs.AddRange(data.ISBNs);
foundBook.Ratings.Clear();
foundBook.Ratings.AddRange(data.Ratings);
foundBook.Contributors.Clear();
foundBook.Contributors.AddRange(data.Contributors);
// Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change
// are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the book.
CollectionReconciler.Reconcile(
foundBook.Ratings,
data.Ratings,
existingRating => existingRating.Source?.ToString() ?? string.Empty,
incomingRating => incomingRating.Source?.ToString() ?? string.Empty,
shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating),
createNew: incomingRating => incomingRating);
// A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a
// contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another field of the book was edited.
CollectionReconciler.Reconcile(
foundBook.Contributors,
data.Contributors,
existingContributor => (existingContributor.MediaContributorId, existingContributor.Role),
incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role),
shouldReplace: (existingContributor, incomingContributor) => false,
createNew: incomingContributor => incomingContributor);
return Result.Updated;
}
/// <summary>
/// Reconciles the tags and genres of <paramref name="foundBook"/> against the ones carried by <paramref name="data"/>, reusing the stored tags and genres whose names already exist.
/// </summary>
/// <param name="foundBook">The tracked book whose tags and genres are reconciled.</param>
/// <param name="data">The book carrying the desired tags and genres.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task ReconcileTagsAndGenresAsync(BookEntity foundBook, BookEntity data, CancellationToken cancellationToken)
{
// Tags and genres are shared across the whole database, so the ones whose names are already stored are reused, and only the missing names are inserted.
List<string> tagNames = [.. data.Tags.Select(tag => tag.Name!)];
List<string> genreNames = [.. data.Genres.Select(genre => genre.Name!)];
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(tag => tagNames.Contains(tag.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => genreNames.Contains(genre.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
CollectionReconciler.Reconcile(
foundBook.Tags,
data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag),
existingTag => existingTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (existingTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
CollectionReconciler.Reconcile(
foundBook.Genres,
data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre),
existingGenre => existingGenre.Name!,
incomingGenre => incomingGenre.Name!,
shouldReplace: (existingGenre, incomingGenre) => false,
createNew: incomingGenre => incomingGenre);
}
/// <summary>
/// Sorts a books query by the given field name, defaulting to <see cref="BookEntity.Title"/>.
/// </summary>
@@ -11,7 +11,6 @@ public static partial class Errors
{
public static class Reading
{
public static Error BookIdCannotBeEmpty => Error.Validation(description: nameof(BookIdCannotBeEmpty));
public static Error LocationRefCannotBeEmpty => Error.Validation(description: nameof(LocationRefCannotBeEmpty));
public static Error ResourceKeyCannotBeEmpty => Error.Validation(description: nameof(ResourceKeyCannotBeEmpty));
public static Error BookNotFound => Error.NotFound(description: nameof(BookNotFound));
@@ -37,6 +37,8 @@ public static partial class Errors
public static Error VolumeNumberMustBeGreaterThanZero => Error.Validation(description: nameof(VolumeNumberMustBeGreaterThanZero));
public static Error BookLibraryCannotBeNull => Error.Validation(description: nameof(BookLibraryCannotBeNull));
public static Error BookPathCannotBeEmpty => Error.Validation(description: nameof(BookPathCannotBeEmpty));
public static Error BookPathMustBeMaximum2048CharactersLong => Error.Validation(description: nameof(BookPathMustBeMaximum2048CharactersLong));
public static Error BookPathMustBeWithinLibraryContentLocations => Error.Validation(description: nameof(BookPathMustBeWithinLibraryContentLocations));
public static Error BookIdCannotBeEmpty => Error.Validation(description: nameof(BookIdCannotBeEmpty));
public static Error BookCoverCannotBeNull => Error.Validation(description: nameof(BookCoverCannotBeNull));
public static Error BookNotFound => Error.NotFound(description: nameof(BookNotFound));
@@ -28,7 +28,7 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
public UpdateBookEndpointSummary()
{
Summary = "Updates an existing book.";
Description = "Updates the details of the book identified by the request. The request is handled by an Admin, who can update the books of all libraries, or by the owner of the library.";
Description = "Updates the details of the book identified by the request, returning the full details of the updated book. The book is updated by an Admin, who can update the books of all libraries, or by the owner of the library of the book.";
RequestParam(r => r.Metadata, "The written content metadata of the book. Required.");
RequestParam(r => r.Metadata!.Title, "The title of the book. Required.");
@@ -1,6 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.Repositories.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
@@ -9,7 +12,9 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
@@ -26,6 +31,9 @@ public class BookRepositoryTests
{
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
private readonly BookRatingEntityFixture _bookRatingEntityFixture = new();
private readonly IsbnEntityFixture _isbnEntityFixture = new();
[Fact]
public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths()
@@ -190,4 +198,180 @@ public class BookRepositoryTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context);
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)];
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)];
context.Books.Add(book);
await context.SaveChangesAsync();
Guid contributorId = book.Contributors[0].Id;
DateTime contributorCreatedOnUtc = book.Contributors[0].CreatedOnUtc;
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
BookEntity? storedBook = await context.Books.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
Assert.NotNull(storedBook);
Assert.Null(storedBook!.UpdatedOnUtc);
BookContributorEntity storedContributor = Assert.Single(storedBook.Contributors);
Assert.Equal(contributorId, storedContributor.Id);
Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
}
[Fact]
public async Task UpdateAsync_WhenOnlyTheMetadataChanged_ShouldStampTheBookAndKeepTheChildRowsUntouched()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-metadata-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context);
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)];
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)];
context.Books.Add(book);
await context.SaveChangesAsync();
Guid contributorId = book.Contributors[0].Id;
DateTime contributorCreatedOnUtc = book.Contributors[0].CreatedOnUtc;
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
incoming.Title = "A brand new title";
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
BookEntity? storedBook = await context.Books.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
Assert.NotNull(storedBook);
Assert.Equal("A brand new title", storedBook!.Title);
Assert.Equal(utcNow, storedBook.UpdatedOnUtc);
Assert.Equal(userId, storedBook.UpdatedBy);
BookContributorEntity storedContributor = Assert.Single(storedBook.Contributors);
Assert.Equal(contributorId, storedContributor.Id);
Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
}
[Fact]
public async Task UpdateAsync_WhenAContributorIsRemoved_ShouldDeleteOnlyThatParticipationAndKeepTheOtherIdentity()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-removecontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context);
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
Guid keptMediaContributorId = Guid.NewGuid();
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId);
BookContributorEntity removedContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid());
book.Contributors = [keptContributor, removedContributor];
context.Books.Add(book);
await context.SaveChangesAsync();
Guid keptContributorId = keptContributor.Id;
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId)];
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
List<BookContributorEntity> storedContributors = await context.Set<BookContributorEntity>().AsNoTracking().Where(contributor => contributor.BookId == book.Id).ToListAsync();
BookContributorEntity storedContributor = Assert.Single(storedContributors);
Assert.Equal(keptContributorId, storedContributor.Id);
Assert.Equal(keptMediaContributorId, storedContributor.MediaContributorId);
}
[Fact]
public async Task UpdateAsync_WhenAContributorIsAdded_ShouldInsertOnlyTheNewParticipationAndKeepTheExistingIdentity()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-addcontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context);
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
Guid keptMediaContributorId = Guid.NewGuid();
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId);
book.Contributors = [keptContributor];
context.Books.Add(book);
await context.SaveChangesAsync();
Guid keptContributorId = keptContributor.Id;
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
Guid addedMediaContributorId = Guid.NewGuid();
incoming.Contributors.Add(_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: addedMediaContributorId));
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
List<BookContributorEntity> storedContributors = await context.Set<BookContributorEntity>().AsNoTracking().Where(contributor => contributor.BookId == book.Id).ToListAsync();
Assert.Equal(2, storedContributors.Count);
Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id);
Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId);
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <param name="userId">The Id of the user reported as the current user.</param>
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
{
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
currentUserService.UserId.Returns(userId);
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.UtcNow.Returns(utcNow);
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Loads a detached copy of a stored book, with its children, so that it can be handed to the repository as the desired state of an edit.
/// </summary>
/// <param name="context">The context that tracks the stored book.</param>
/// <param name="bookId">The Id of the book to load.</param>
/// <returns>The detached copy of the book.</returns>
private static async Task<BookEntity> LoadDetachedBookAsync(LuminaDbContext context, Guid bookId)
{
return await context.Books
.AsNoTracking()
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.Contributors)
.FirstAsync(book => book.Id == bookId);
}
}