Refactors the book, artist, and album slices across the stack

This commit is contained in:
BinaryAlley committed 2026-09-17 13:30:48 -07:00
1 parent 8aaf9fe64e
commit ea6eb9f796
439 files changed
+28235 -3156

No files matched your search

@@ -0,0 +1,183 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="AlbumEntity"/> entity.
/// </summary>
public class AlbumConfiguration : IEntityTypeConfiguration<AlbumEntity>
{
/// <summary>
/// Configures the <see cref="AlbumEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<AlbumEntity> builder)
{
builder.ToTable("Albums");
builder.HasKey(album => album.Id);
builder.Property(album => album.Id)
.ValueGeneratedNever()
.HasColumnOrder(0);
builder.Property(album => album.ArtistId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(album => album.LibraryId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(album => album.Title)
.IsRequired()
.HasMaxLength(255)
.HasColumnOrder(3);
builder.Property(album => album.OriginalTitle)
.HasMaxLength(255)
.HasColumnOrder(4);
builder.Property(album => album.Description)
.HasMaxLength(2000)
.HasColumnOrder(5);
builder.Property(album => album.OriginalReleaseDate)
.HasColumnOrder(6);
builder.Property(album => album.OriginalReleaseYear)
.HasColumnOrder(7);
builder.Property(album => album.ReReleaseDate)
.HasColumnOrder(8);
builder.Property(album => album.ReReleaseYear)
.HasColumnOrder(9);
builder.Property(album => album.ReleaseCountry)
.HasConversion<string>()
.HasMaxLength(2)
.HasColumnOrder(10);
builder.Property(album => album.ReleaseVersion)
.HasColumnOrder(11);
builder.Property(album => album.LanguageCode)
.HasColumnOrder(12);
builder.Property(album => album.LanguageName)
.HasColumnOrder(13);
builder.Property(album => album.LanguageNativeName)
.HasColumnOrder(14);
builder.Property(album => album.OriginalLanguageCode)
.HasColumnOrder(15);
builder.Property(album => album.OriginalLanguageName)
.HasColumnOrder(16);
builder.Property(album => album.OriginalLanguageNativeName)
.HasColumnOrder(17);
builder.Property(album => album.ReleaseType)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(18);
builder.Property(album => album.ReleaseStatus)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(19);
builder.Property(album => album.TotalDiscs)
.HasColumnOrder(20);
builder.Property(album => album.TotalTracks)
.HasColumnOrder(21);
builder.Property(album => album.MediaFormat)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(22);
builder.Property(album => album.Barcode)
.HasMaxLength(13)
.HasColumnOrder(23);
builder.Property(album => album.CatalogNumber)
.HasMaxLength(50)
.HasColumnOrder(24);
builder.Property(album => album.MusicBrainzReleaseId)
.HasColumnOrder(25);
builder.Property(album => album.MusicBrainzReleaseGroupId)
.HasColumnOrder(26);
builder.Property(album => album.MusicBrainzReleaseArtistId)
.HasColumnOrder(27);
builder.Property(album => album.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(28);
builder.Property(album => album.CreatedBy)
.IsRequired()
.HasColumnOrder(29);
builder.Property(album => album.UpdatedOnUtc)
.HasColumnOrder(30);
builder.Property(album => album.UpdatedBy)
.HasColumnOrder(31);
builder.HasOne(album => album.Artist)
.WithMany(artist => artist.Albums)
.HasForeignKey(album => album.ArtistId)
.OnDelete(DeleteBehavior.Cascade);
// since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates,
// we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key
builder.HasMany(album => album.Tags)
.WithMany()
.UsingEntity<Dictionary<string, object>>(
"AlbumTags",
j => j.HasOne<TagEntity>()
.WithMany()
.HasForeignKey("TagId"),
j => j.HasOne<AlbumEntity>()
.WithMany()
.HasForeignKey("AlbumId"),
j =>
{
j.HasKey("AlbumId", "TagId");
j.ToTable("AlbumTags");
});
builder.HasMany(album => album.Genres)
.WithMany()
.UsingEntity<Dictionary<string, object>>(
"AlbumGenres",
j => j.HasOne<GenreEntity>()
.WithMany()
.HasForeignKey("GenreId"),
j => j.HasOne<AlbumEntity>()
.WithMany()
.HasForeignKey("AlbumId"),
j =>
{
j.HasKey("AlbumId", "GenreId");
j.ToTable("AlbumGenres");
});
builder.OwnsMany(album => album.Ratings, ratingBuilder =>
{
ratingBuilder.ToTable("AlbumRatings");
ratingBuilder.WithOwner()
.HasForeignKey("AlbumId");
ratingBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
ratingBuilder.HasKey("Id");
ratingBuilder.Property(rating => rating.Value)
.HasColumnType("decimal(3,2)")
.IsRequired();
ratingBuilder.Property(rating => rating.MaxValue)
.HasColumnType("decimal(3,2)")
.IsRequired();
ratingBuilder.Property(rating => rating.VoteCount)
.IsRequired(false);
ratingBuilder.Property(rating => rating.Source)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired(false);
});
builder.HasMany(album => album.Contributors)
.WithOne()
.HasForeignKey(contributor => contributor.AlbumId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasIndex(album => new { album.ArtistId, album.Title });
builder.HasIndex(album => new { album.LibraryId, album.Title });
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="AlbumContributorEntity"/> entity.
/// </summary>
public class AlbumContributorConfiguration : IEntityTypeConfiguration<AlbumContributorEntity>
{
/// <summary>
/// Configures the <see cref="AlbumContributorEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<AlbumContributorEntity> builder)
{
builder.ToTable("AlbumContributors");
builder.HasKey(albumContributor => albumContributor.Id);
builder.Property(albumContributor => albumContributor.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
builder.Property(albumContributor => albumContributor.AlbumId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(albumContributor => albumContributor.MediaContributorId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(albumContributor => albumContributor.Role)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired()
.HasColumnOrder(3);
// audit
builder.Property(albumContributor => albumContributor.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(4);
builder.Property(albumContributor => albumContributor.CreatedBy)
.IsRequired()
.HasColumnOrder(5);
builder.Property(albumContributor => albumContributor.UpdatedOnUtc)
.HasColumnOrder(6);
builder.Property(albumContributor => albumContributor.UpdatedBy)
.HasColumnOrder(7);
builder.HasIndex(albumContributor => new { albumContributor.AlbumId, albumContributor.MediaContributorId, albumContributor.Role })
.IsUnique();
builder.HasIndex(albumContributor => albumContributor.MediaContributorId);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="ArtistEntity"/> entity.
/// </summary>
public class ArtistConfiguration : IEntityTypeConfiguration<ArtistEntity>
{
/// <summary>
/// Configures the <see cref="ArtistEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<ArtistEntity> builder)
{
builder.ToTable("Artists");
builder.HasKey(artist => artist.Id);
builder.Property(artist => artist.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
builder.Property(artist => artist.LibraryId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(artist => artist.Name)
.IsRequired()
.HasMaxLength(255)
.HasColumnOrder(2);
builder.Property(artist => artist.Website)
.HasMaxLength(2048)
.HasColumnOrder(3);
builder.Property(artist => artist.MusicBrainzArtistId)
.HasColumnOrder(4);
builder.Property(artist => artist.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(5);
builder.Property(artist => artist.CreatedBy)
.IsRequired()
.HasColumnOrder(6);
builder.Property(artist => artist.UpdatedOnUtc)
.HasColumnOrder(7);
builder.Property(artist => artist.UpdatedBy)
.HasColumnOrder(8);
builder.HasMany(artist => artist.Contributors)
.WithOne()
.HasForeignKey(contributor => contributor.ArtistId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasIndex(artist => new { artist.LibraryId, artist.Name })
.IsUnique(); // the same artist cannot appear twice in the same library
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="ArtistContributorEntity"/> entity.
/// </summary>
public class ArtistContributorConfiguration : IEntityTypeConfiguration<ArtistContributorEntity>
{
/// <summary>
/// Configures the <see cref="ArtistContributorEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<ArtistContributorEntity> builder)
{
builder.ToTable("ArtistContributors");
builder.HasKey(artistContributor => artistContributor.Id);
builder.Property(artistContributor => artistContributor.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
builder.Property(artistContributor => artistContributor.ArtistId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(artistContributor => artistContributor.MediaContributorId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(artistContributor => artistContributor.Role)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired()
.HasColumnOrder(3);
// audit
builder.Property(artistContributor => artistContributor.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(4);
builder.Property(artistContributor => artistContributor.CreatedBy)
.IsRequired()
.HasColumnOrder(5);
builder.Property(artistContributor => artistContributor.UpdatedOnUtc)
.HasColumnOrder(6);
builder.Property(artistContributor => artistContributor.UpdatedBy)
.HasColumnOrder(7);
builder.HasIndex(artistContributor => new { artistContributor.ArtistId, artistContributor.MediaContributorId, artistContributor.Role })
.IsUnique();
builder.HasIndex(artistContributor => artistContributor.MediaContributorId);
}
}
@@ -149,17 +149,13 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
builder.Property(book => book.MetadataProvider)
.HasMaxLength(100)
.HasColumnOrder(40);
builder.Property(book => book.CreatedOnUtc)
.HasColumnOrder(30);
builder.Property(book => book.UpdatedOnUtc)
.HasColumnOrder(31);
builder.HasMany(book => book.BookContributors)
builder.HasMany(book => book.Contributors)
.WithOne()
.HasForeignKey(bookContributor => bookContributor.BookId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(book => book.BookArtwork)
builder.HasMany(book => book.Artwork)
.WithOne()
.HasForeignKey(bookArtwork => bookArtwork.BookId)
.OnDelete(DeleteBehavior.Cascade);
@@ -0,0 +1,224 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="TrackEntity"/> entity.
/// </summary>
public class TrackConfiguration : IEntityTypeConfiguration<TrackEntity>
{
/// <summary>
/// Configures the <see cref="TrackEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<TrackEntity> builder)
{
builder.ToTable("Tracks");
builder.HasKey(track => track.Id);
builder.Property(track => track.Id)
.ValueGeneratedNever()
.HasColumnOrder(0);
builder.Property(track => track.AlbumId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(track => track.LibraryId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(track => track.Path)
.IsRequired()
.HasMaxLength(2048)
.HasColumnOrder(3);
builder.Property(track => track.Title)
.IsRequired()
.HasMaxLength(255)
.HasColumnOrder(4);
builder.Property(track => track.OriginalTitle)
.HasMaxLength(255)
.HasColumnOrder(5);
builder.Property(track => track.Description)
.HasMaxLength(2000)
.HasColumnOrder(6);
builder.Property(track => track.OriginalReleaseDate)
.HasColumnOrder(7);
builder.Property(track => track.OriginalReleaseYear)
.HasColumnOrder(8);
builder.Property(track => track.ReReleaseDate)
.HasColumnOrder(9);
builder.Property(track => track.ReReleaseYear)
.HasColumnOrder(10);
builder.Property(track => track.ReleaseCountry)
.HasConversion<string>()
.HasMaxLength(2)
.HasColumnOrder(11);
builder.Property(track => track.ReleaseVersion)
.HasColumnOrder(12);
builder.Property(track => track.LanguageCode)
.HasColumnOrder(13);
builder.Property(track => track.LanguageName)
.HasColumnOrder(14);
builder.Property(track => track.LanguageNativeName)
.HasColumnOrder(15);
builder.Property(track => track.OriginalLanguageCode)
.HasColumnOrder(16);
builder.Property(track => track.OriginalLanguageName)
.HasColumnOrder(17);
builder.Property(track => track.OriginalLanguageNativeName)
.HasColumnOrder(18);
builder.Property(track => track.DurationInSeconds)
.HasColumnOrder(19);
builder.Property(track => track.SampleRate)
.HasColumnOrder(20);
builder.Property(track => track.Channels)
.HasColumnOrder(21);
builder.Property(track => track.BitDepth)
.HasColumnOrder(22);
builder.Property(track => track.AudioCodec)
.HasMaxLength(50)
.HasColumnOrder(23);
builder.Property(track => track.Bitrate)
.HasColumnOrder(24);
builder.Property(track => track.TrackNumber)
.HasColumnOrder(25);
builder.Property(track => track.DiscNumber)
.HasColumnOrder(26);
builder.Property(track => track.Script)
.HasMaxLength(50)
.HasColumnOrder(27);
builder.Property(track => track.Key)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(28);
builder.Property(track => track.Bpm)
.HasColumnOrder(29);
builder.Property(track => track.Work)
.HasMaxLength(255)
.HasColumnOrder(30);
builder.Property(track => track.MusicBrainzRecordingId)
.HasColumnOrder(31);
builder.Property(track => track.MusicBrainzTrackId)
.HasColumnOrder(32);
builder.Property(track => track.MusicBrainzWorkId)
.HasColumnOrder(33);
builder.Property(track => track.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(34);
builder.Property(track => track.CreatedBy)
.IsRequired()
.HasColumnOrder(35);
builder.Property(track => track.UpdatedOnUtc)
.HasColumnOrder(36);
builder.Property(track => track.UpdatedBy)
.HasColumnOrder(37);
builder.HasOne(track => track.Album)
.WithMany(album => album.Tracks)
.HasForeignKey(track => track.AlbumId)
.OnDelete(DeleteBehavior.Cascade);
// since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates,
// we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key
builder.HasMany(track => track.Tags)
.WithMany()
.UsingEntity<Dictionary<string, object>>(
"TrackTags",
j => j.HasOne<TagEntity>()
.WithMany()
.HasForeignKey("TagId"),
j => j.HasOne<TrackEntity>()
.WithMany()
.HasForeignKey("TrackId"),
j =>
{
j.HasKey("TrackId", "TagId");
j.ToTable("TrackTags");
});
builder.HasMany(track => track.Genres)
.WithMany()
.UsingEntity<Dictionary<string, object>>(
"TrackGenres",
j => j.HasOne<GenreEntity>()
.WithMany()
.HasForeignKey("GenreId"),
j => j.HasOne<TrackEntity>()
.WithMany()
.HasForeignKey("TrackId"),
j =>
{
j.HasKey("TrackId", "GenreId");
j.ToTable("TrackGenres");
});
builder.OwnsMany(track => track.Ratings, ratingBuilder =>
{
ratingBuilder.ToTable("TrackRatings");
ratingBuilder.WithOwner()
.HasForeignKey("TrackId");
ratingBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
ratingBuilder.HasKey("Id");
ratingBuilder.Property(rating => rating.Value)
.HasColumnType("decimal(3,2)")
.IsRequired();
ratingBuilder.Property(rating => rating.MaxValue)
.HasColumnType("decimal(3,2)")
.IsRequired();
ratingBuilder.Property(rating => rating.VoteCount)
.IsRequired(false);
ratingBuilder.Property(rating => rating.Source)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired(false);
});
builder.HasMany(track => track.Contributors)
.WithOne()
.HasForeignKey(contributor => contributor.TrackId)
.OnDelete(DeleteBehavior.Cascade);
builder.OwnsMany(track => track.Moods, moodBuilder =>
{
moodBuilder.ToTable("TrackMoods");
moodBuilder.WithOwner()
.HasForeignKey("TrackId");
moodBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
moodBuilder.HasKey("Id");
moodBuilder.Property(mood => mood.Name)
.IsRequired()
.HasMaxLength(50);
});
builder.OwnsMany(track => track.Isrcs, isrcBuilder =>
{
isrcBuilder.ToTable("TrackIsrcs");
isrcBuilder.WithOwner()
.HasForeignKey("TrackId");
isrcBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
isrcBuilder.HasKey("Id");
isrcBuilder.Property(isrc => isrc.Value)
.HasColumnName("ISRC")
.HasMaxLength(12)
.IsRequired();
});
builder.HasIndex(track => new { track.AlbumId, track.TrackNumber });
builder.HasIndex(track => new { track.LibraryId, track.Path })
.IsUnique(); // the same physical track file cannot appear twice in the same library
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="TrackContributorEntity"/> entity.
/// </summary>
public class TrackContributorConfiguration : IEntityTypeConfiguration<TrackContributorEntity>
{
/// <summary>
/// Configures the <see cref="TrackContributorEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<TrackContributorEntity> builder)
{
builder.ToTable("TrackContributors");
builder.HasKey(trackContributor => trackContributor.Id);
builder.Property(trackContributor => trackContributor.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
builder.Property(trackContributor => trackContributor.TrackId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(trackContributor => trackContributor.MediaContributorId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(trackContributor => trackContributor.Role)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired()
.HasColumnOrder(3);
// audit
builder.Property(trackContributor => trackContributor.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(4);
builder.Property(trackContributor => trackContributor.CreatedBy)
.IsRequired()
.HasColumnOrder(5);
builder.Property(trackContributor => trackContributor.UpdatedOnUtc)
.HasColumnOrder(6);
builder.Property(trackContributor => trackContributor.UpdatedBy)
.HasColumnOrder(7);
builder.HasIndex(trackContributor => new { trackContributor.TrackId, trackContributor.MediaContributorId, trackContributor.Role })
.IsUnique();
builder.HasIndex(trackContributor => trackContributor.MediaContributorId);
}
}
@@ -0,0 +1,680 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsMusicLibraryAndCanonicalContributorRoles : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_BookContributors_BookId_MediaContributorId",
table: "BookContributors");
migrationBuilder.DropColumn(
name: "RoleName",
table: "BookContributors");
migrationBuilder.RenameColumn(
name: "RoleCategory",
table: "BookContributors",
newName: "Role");
migrationBuilder.AlterColumn<DateTime>(
name: "UpdatedOnUtc",
table: "BookContributors",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 6)
.OldAnnotation("Relational:ColumnOrder", 7);
migrationBuilder.AlterColumn<Guid>(
name: "UpdatedBy",
table: "BookContributors",
type: "TEXT",
nullable: true,
oldClrType: typeof(Guid),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 7)
.OldAnnotation("Relational:ColumnOrder", 8);
migrationBuilder.AlterColumn<DateTime>(
name: "CreatedOnUtc",
table: "BookContributors",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 4)
.OldAnnotation("Relational:ColumnOrder", 5);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "BookContributors",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 5)
.OldAnnotation("Relational:ColumnOrder", 6);
migrationBuilder.AlterColumn<string>(
name: "Role",
table: "BookContributors",
type: "TEXT",
maxLength: 50,
nullable: false,
oldClrType: typeof(string),
oldType: "TEXT",
oldMaxLength: 50)
.Annotation("Relational:ColumnOrder", 3)
.OldAnnotation("Relational:ColumnOrder", 4);
migrationBuilder.CreateTable(
name: "Artists",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
Website = table.Column<string>(type: "TEXT", maxLength: 2048, nullable: true),
MusicBrainzArtistId = table.Column<Guid>(type: "TEXT", nullable: true),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Artists", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Albums",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
ArtistId = table.Column<Guid>(type: "TEXT", nullable: false),
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
OriginalTitle = table.Column<string>(type: "TEXT", maxLength: 255, nullable: true),
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
OriginalReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
OriginalReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
ReReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
ReReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
ReleaseCountry = table.Column<string>(type: "TEXT", maxLength: 2, nullable: true),
ReleaseVersion = table.Column<string>(type: "TEXT", nullable: true),
LanguageCode = table.Column<string>(type: "TEXT", nullable: true),
LanguageName = table.Column<string>(type: "TEXT", nullable: true),
LanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageCode = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageName = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
ReleaseType = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
ReleaseStatus = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
TotalDiscs = table.Column<int>(type: "INTEGER", nullable: true),
TotalTracks = table.Column<int>(type: "INTEGER", nullable: false),
MediaFormat = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
Barcode = table.Column<string>(type: "TEXT", maxLength: 13, nullable: true),
CatalogNumber = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
MusicBrainzReleaseId = table.Column<Guid>(type: "TEXT", nullable: true),
MusicBrainzReleaseGroupId = table.Column<Guid>(type: "TEXT", nullable: true),
MusicBrainzReleaseArtistId = table.Column<Guid>(type: "TEXT", nullable: true),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Albums", x => x.Id);
table.ForeignKey(
name: "FK_Albums_Artists_ArtistId",
column: x => x.ArtistId,
principalTable: "Artists",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ArtistContributors",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
ArtistId = table.Column<Guid>(type: "TEXT", nullable: false),
MediaContributorId = table.Column<Guid>(type: "TEXT", nullable: false),
Role = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ArtistContributors", x => x.Id);
table.ForeignKey(
name: "FK_ArtistContributors_Artists_ArtistId",
column: x => x.ArtistId,
principalTable: "Artists",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AlbumContributors",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
AlbumId = table.Column<Guid>(type: "TEXT", nullable: false),
MediaContributorId = table.Column<Guid>(type: "TEXT", nullable: false),
Role = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AlbumContributors", x => x.Id);
table.ForeignKey(
name: "FK_AlbumContributors_Albums_AlbumId",
column: x => x.AlbumId,
principalTable: "Albums",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AlbumGenres",
columns: table => new
{
AlbumId = table.Column<Guid>(type: "TEXT", nullable: false),
GenreId = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AlbumGenres", x => new { x.AlbumId, x.GenreId });
table.ForeignKey(
name: "FK_AlbumGenres_Albums_AlbumId",
column: x => x.AlbumId,
principalTable: "Albums",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AlbumGenres_Genres_GenreId",
column: x => x.GenreId,
principalTable: "Genres",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AlbumRatings",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Source = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
AlbumId = table.Column<Guid>(type: "TEXT", nullable: false),
Value = table.Column<decimal>(type: "decimal(3,2)", nullable: false),
MaxValue = table.Column<decimal>(type: "decimal(3,2)", nullable: false),
VoteCount = table.Column<int>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AlbumRatings", x => x.Id);
table.ForeignKey(
name: "FK_AlbumRatings_Albums_AlbumId",
column: x => x.AlbumId,
principalTable: "Albums",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AlbumTags",
columns: table => new
{
AlbumId = table.Column<Guid>(type: "TEXT", nullable: false),
TagId = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AlbumTags", x => new { x.AlbumId, x.TagId });
table.ForeignKey(
name: "FK_AlbumTags_Albums_AlbumId",
column: x => x.AlbumId,
principalTable: "Albums",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AlbumTags_Tags_TagId",
column: x => x.TagId,
principalTable: "Tags",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Tracks",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
AlbumId = table.Column<Guid>(type: "TEXT", nullable: false),
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false),
Path = table.Column<string>(type: "TEXT", maxLength: 2048, nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
OriginalTitle = table.Column<string>(type: "TEXT", maxLength: 255, nullable: true),
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
OriginalReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
OriginalReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
ReReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
ReReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
ReleaseCountry = table.Column<string>(type: "TEXT", maxLength: 2, nullable: true),
ReleaseVersion = table.Column<string>(type: "TEXT", nullable: true),
LanguageCode = table.Column<string>(type: "TEXT", nullable: true),
LanguageName = table.Column<string>(type: "TEXT", nullable: true),
LanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageCode = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageName = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
DurationInSeconds = table.Column<int>(type: "INTEGER", nullable: false),
SampleRate = table.Column<int>(type: "INTEGER", nullable: false),
Channels = table.Column<int>(type: "INTEGER", nullable: false),
BitDepth = table.Column<int>(type: "INTEGER", nullable: true),
AudioCodec = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
Bitrate = table.Column<int>(type: "INTEGER", nullable: true),
TrackNumber = table.Column<int>(type: "INTEGER", nullable: false),
DiscNumber = table.Column<int>(type: "INTEGER", nullable: true),
Script = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
Key = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
Bpm = table.Column<int>(type: "INTEGER", nullable: true),
Work = table.Column<string>(type: "TEXT", maxLength: 255, nullable: true),
MusicBrainzRecordingId = table.Column<Guid>(type: "TEXT", nullable: true),
MusicBrainzTrackId = table.Column<Guid>(type: "TEXT", nullable: true),
MusicBrainzWorkId = table.Column<Guid>(type: "TEXT", nullable: true),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Tracks", x => x.Id);
table.ForeignKey(
name: "FK_Tracks_Albums_AlbumId",
column: x => x.AlbumId,
principalTable: "Albums",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "TrackContributors",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
TrackId = table.Column<Guid>(type: "TEXT", nullable: false),
MediaContributorId = table.Column<Guid>(type: "TEXT", nullable: false),
Role = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_TrackContributors", x => x.Id);
table.ForeignKey(
name: "FK_TrackContributors_Tracks_TrackId",
column: x => x.TrackId,
principalTable: "Tracks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "TrackGenres",
columns: table => new
{
TrackId = table.Column<Guid>(type: "TEXT", nullable: false),
GenreId = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TrackGenres", x => new { x.TrackId, x.GenreId });
table.ForeignKey(
name: "FK_TrackGenres_Genres_GenreId",
column: x => x.GenreId,
principalTable: "Genres",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_TrackGenres_Tracks_TrackId",
column: x => x.TrackId,
principalTable: "Tracks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "TrackIsrcs",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
ISRC = table.Column<string>(type: "TEXT", maxLength: 12, nullable: false),
TrackId = table.Column<Guid>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TrackIsrcs", x => x.Id);
table.ForeignKey(
name: "FK_TrackIsrcs_Tracks_TrackId",
column: x => x.TrackId,
principalTable: "Tracks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "TrackMoods",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
TrackId = table.Column<Guid>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TrackMoods", x => x.Id);
table.ForeignKey(
name: "FK_TrackMoods_Tracks_TrackId",
column: x => x.TrackId,
principalTable: "Tracks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "TrackRatings",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Source = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
TrackId = table.Column<Guid>(type: "TEXT", nullable: false),
Value = table.Column<decimal>(type: "decimal(3,2)", nullable: false),
MaxValue = table.Column<decimal>(type: "decimal(3,2)", nullable: false),
VoteCount = table.Column<int>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_TrackRatings", x => x.Id);
table.ForeignKey(
name: "FK_TrackRatings_Tracks_TrackId",
column: x => x.TrackId,
principalTable: "Tracks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "TrackTags",
columns: table => new
{
TrackId = table.Column<Guid>(type: "TEXT", nullable: false),
TagId = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TrackTags", x => new { x.TrackId, x.TagId });
table.ForeignKey(
name: "FK_TrackTags_Tags_TagId",
column: x => x.TagId,
principalTable: "Tags",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_TrackTags_Tracks_TrackId",
column: x => x.TrackId,
principalTable: "Tracks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_BookContributors_BookId_MediaContributorId_Role",
table: "BookContributors",
columns: new[] { "BookId", "MediaContributorId", "Role" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AlbumContributors_AlbumId_MediaContributorId_Role",
table: "AlbumContributors",
columns: new[] { "AlbumId", "MediaContributorId", "Role" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AlbumContributors_MediaContributorId",
table: "AlbumContributors",
column: "MediaContributorId");
migrationBuilder.CreateIndex(
name: "IX_AlbumGenres_GenreId",
table: "AlbumGenres",
column: "GenreId");
migrationBuilder.CreateIndex(
name: "IX_AlbumRatings_AlbumId",
table: "AlbumRatings",
column: "AlbumId");
migrationBuilder.CreateIndex(
name: "IX_Albums_ArtistId_Title",
table: "Albums",
columns: new[] { "ArtistId", "Title" });
migrationBuilder.CreateIndex(
name: "IX_Albums_LibraryId_Title",
table: "Albums",
columns: new[] { "LibraryId", "Title" });
migrationBuilder.CreateIndex(
name: "IX_AlbumTags_TagId",
table: "AlbumTags",
column: "TagId");
migrationBuilder.CreateIndex(
name: "IX_ArtistContributors_ArtistId_MediaContributorId_Role",
table: "ArtistContributors",
columns: new[] { "ArtistId", "MediaContributorId", "Role" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_ArtistContributors_MediaContributorId",
table: "ArtistContributors",
column: "MediaContributorId");
migrationBuilder.CreateIndex(
name: "IX_Artists_LibraryId_Name",
table: "Artists",
columns: new[] { "LibraryId", "Name" });
migrationBuilder.CreateIndex(
name: "IX_TrackContributors_MediaContributorId",
table: "TrackContributors",
column: "MediaContributorId");
migrationBuilder.CreateIndex(
name: "IX_TrackContributors_TrackId_MediaContributorId_Role",
table: "TrackContributors",
columns: new[] { "TrackId", "MediaContributorId", "Role" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_TrackGenres_GenreId",
table: "TrackGenres",
column: "GenreId");
migrationBuilder.CreateIndex(
name: "IX_TrackIsrcs_TrackId",
table: "TrackIsrcs",
column: "TrackId");
migrationBuilder.CreateIndex(
name: "IX_TrackMoods_TrackId",
table: "TrackMoods",
column: "TrackId");
migrationBuilder.CreateIndex(
name: "IX_TrackRatings_TrackId",
table: "TrackRatings",
column: "TrackId");
migrationBuilder.CreateIndex(
name: "IX_Tracks_AlbumId_TrackNumber",
table: "Tracks",
columns: new[] { "AlbumId", "TrackNumber" });
migrationBuilder.CreateIndex(
name: "IX_Tracks_LibraryId_Path",
table: "Tracks",
columns: new[] { "LibraryId", "Path" });
migrationBuilder.CreateIndex(
name: "IX_TrackTags_TagId",
table: "TrackTags",
column: "TagId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AlbumContributors");
migrationBuilder.DropTable(
name: "AlbumGenres");
migrationBuilder.DropTable(
name: "AlbumRatings");
migrationBuilder.DropTable(
name: "AlbumTags");
migrationBuilder.DropTable(
name: "ArtistContributors");
migrationBuilder.DropTable(
name: "TrackContributors");
migrationBuilder.DropTable(
name: "TrackGenres");
migrationBuilder.DropTable(
name: "TrackIsrcs");
migrationBuilder.DropTable(
name: "TrackMoods");
migrationBuilder.DropTable(
name: "TrackRatings");
migrationBuilder.DropTable(
name: "TrackTags");
migrationBuilder.DropTable(
name: "Tracks");
migrationBuilder.DropTable(
name: "Albums");
migrationBuilder.DropTable(
name: "Artists");
migrationBuilder.DropIndex(
name: "IX_BookContributors_BookId_MediaContributorId_Role",
table: "BookContributors");
migrationBuilder.RenameColumn(
name: "Role",
table: "BookContributors",
newName: "RoleCategory");
migrationBuilder.AlterColumn<DateTime>(
name: "UpdatedOnUtc",
table: "BookContributors",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 7)
.OldAnnotation("Relational:ColumnOrder", 6);
migrationBuilder.AlterColumn<Guid>(
name: "UpdatedBy",
table: "BookContributors",
type: "TEXT",
nullable: true,
oldClrType: typeof(Guid),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 8)
.OldAnnotation("Relational:ColumnOrder", 7);
migrationBuilder.AlterColumn<DateTime>(
name: "CreatedOnUtc",
table: "BookContributors",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 5)
.OldAnnotation("Relational:ColumnOrder", 4);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "BookContributors",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 6)
.OldAnnotation("Relational:ColumnOrder", 5);
migrationBuilder.AlterColumn<string>(
name: "RoleCategory",
table: "BookContributors",
type: "TEXT",
maxLength: 50,
nullable: false,
oldClrType: typeof(string),
oldType: "TEXT",
oldMaxLength: 50)
.Annotation("Relational:ColumnOrder", 4)
.OldAnnotation("Relational:ColumnOrder", 3);
migrationBuilder.AddColumn<string>(
name: "RoleName",
table: "BookContributors",
type: "TEXT",
maxLength: 100,
nullable: false,
defaultValue: "")
.Annotation("Relational:ColumnOrder", 3);
migrationBuilder.CreateIndex(
name: "IX_BookContributors_BookId_MediaContributorId",
table: "BookContributors",
columns: new[] { "BookId", "MediaContributorId" });
}
}
}
@@ -2,12 +2,12 @@
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
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.Core.Repositories.Books.Specifications;
using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -25,7 +25,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Books;
namespace Lumina.DataAccess.Core.Repositories.BookLibrary;
/// <summary>
/// Repository for books.
@@ -55,13 +55,13 @@ internal sealed class BookRepository : IBookRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(BookEntity book, CancellationToken cancellationToken)
{
bool bookExists = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (bookExists)
bool doesBookExist = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesBookExist)
return Errors.WrittenContent.BookAlreadyExists;
// A book is unique within its library by its file system path, so the same file can never be registered twice in the same library.
bool bookPathExists = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.LibraryId == book.LibraryId && repositoryBook.Path == book.Path, cancellationToken: cancellationToken).ConfigureAwait(false);
if (bookPathExists)
bool doesBookPathExist = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.LibraryId == book.LibraryId && repositoryBook.Path == book.Path, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesBookPathExist)
return Errors.WrittenContent.BookAlreadyExists;
// Fetch existing tags and genres.
@@ -87,20 +87,20 @@ internal sealed class BookRepository : IBookRepository
/// <param name="id">The Id of the book to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="BookEntity"/>, or an error.</returns>
public async Task<Result<BookEntity?>> GetByIdAsync(Guid id, bool includeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
public async Task<Result<BookEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
IQueryable<BookEntity> query = _luminaDbContext.Books;
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (includeNavigationProperties)
if (shouldIncludeNavigationProperties)
{
query = query
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookContributors)
.Include(book => book.BookArtwork);
.Include(book => book.Contributors)
.Include(book => book.Artwork);
}
return await query.FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false);
}
@@ -113,24 +113,24 @@ internal sealed class BookRepository : IBookRepository
/// <param name="sortBy">The name of the fields by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="includeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{BookEntity}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<BookEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool includeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
public async Task<Result<PaginatedResultDto<BookEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
IQueryable<BookEntity> booksQuery = _luminaDbContext.Books;
if (!shouldTrackEntities)
booksQuery = booksQuery.AsNoTracking();
if (includeNavigationProperties)
if (shouldIncludeNavigationProperties)
{
booksQuery = booksQuery
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookContributors)
.Include(book => book.BookArtwork);
.Include(book => book.Contributors)
.Include(book => book.Artwork);
}
// Books should always be retrieved only per owning libraries.
@@ -190,11 +190,11 @@ internal sealed class BookRepository : IBookRepository
/// <param name="sortBy">The name of the fields by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="includeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{BookLiteRow}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<BookLiteRow>>> GetAllLiteAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool includeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
public async Task<Result<PaginatedResultDto<BookLiteRow>>> GetAllLiteAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
// Books should always be retrieved only per owning libraries.
if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty)
@@ -204,15 +204,15 @@ internal sealed class BookRepository : IBookRepository
IQueryable<BookEntity> booksQuery = _luminaDbContext.Books;
if (!shouldTrackEntities)
booksQuery = booksQuery.AsNoTracking();
if (includeNavigationProperties)
if (shouldIncludeNavigationProperties)
{
booksQuery = booksQuery
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookContributors)
.Include(book => book.BookArtwork);
.Include(book => book.Contributors)
.Include(book => book.Artwork);
}
booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId);
@@ -229,7 +229,7 @@ internal sealed class BookRepository : IBookRepository
Id = book.Id,
Title = book.Title,
ReleaseYear = book.ReReleaseYear ?? book.OriginalReleaseYear,
CoverPath = book.BookArtwork
CoverPath = book.Artwork
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
@@ -281,8 +281,8 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.BookContributors)
.Include(book => book.BookArtwork)
.Include(book => book.Contributors)
.Include(book => book.Artwork)
.Where(book => book.LibraryId == libraryId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
@@ -300,7 +300,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.BookArtwork)
.Include(book => book.Artwork)
.FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false);
}
@@ -319,7 +319,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.BookContributors)
.Include(book => book.Contributors)
.Where(book => book.LibraryId == libraryId
&& book.MetadataStatus != MetadataStatus.Enriched
&& (lastPath == null || book.Path.CompareTo(lastPath) > 0))
@@ -355,9 +355,9 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.BookArtwork)
.Include(book => book.Artwork)
.Where(book => book.LibraryId == libraryId
&& !book.BookArtwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched)
&& !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched)
&& (lastPath == null || book.Path.CompareTo(lastPath) > 0))
.OrderBy(book => book.Path)
.Take(pageSize)
@@ -374,7 +374,7 @@ internal sealed class BookRepository : IBookRepository
{
return await _luminaDbContext.Books
.CountAsync(book => book.LibraryId == libraryId
&& !book.BookArtwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched), cancellationToken)
&& !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched), cancellationToken)
.ConfigureAwait(false);
}
@@ -466,15 +466,15 @@ internal sealed class BookRepository : IBookRepository
private sealed record AuthorRow(Guid BookId, string DisplayName);
/// <summary>
/// Deletes the book identified by <paramref name="bookId"/>.
/// Deletes the book identified by <paramref name="id"/>.
/// </summary>
/// <param name="bookId">The Id of the book to delete.</param>
/// <param name="id">The Id of the book to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteAsync(Guid bookId, CancellationToken cancellationToken)
public async Task<Result<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
BookEntity? book = await _luminaDbContext.Books
.FirstOrDefaultAsync(repositoryBook => repositoryBook.Id == bookId, cancellationToken).ConfigureAwait(false);
.FirstOrDefaultAsync(repositoryBook => repositoryBook.Id == id, cancellationToken).ConfigureAwait(false);
if (book is null)
return Errors.WrittenContent.BookNotFound;
@@ -495,8 +495,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookContributors)
.Include(book => book.BookArtwork)
.Include(book => book.Contributors)
.FirstOrDefaultAsync(book => book.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundBook is null)
return Errors.WrittenContent.BookNotFound;
@@ -538,10 +537,8 @@ internal sealed class BookRepository : IBookRepository
foundBook.ISBNs.AddRange(data.ISBNs);
foundBook.Ratings.Clear();
foundBook.Ratings.AddRange(data.Ratings);
foundBook.BookContributors.Clear();
foundBook.BookContributors.AddRange(data.BookContributors);
foundBook.BookArtwork.Clear();
foundBook.BookArtwork.AddRange(data.BookArtwork);
foundBook.Contributors.Clear();
foundBook.Contributors.AddRange(data.Contributors);
return Result.Updated;
}
@@ -8,7 +8,7 @@ using System.Linq.Expressions;
using System.Reflection;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Books.Specifications;
namespace Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications;
/// <summary>
/// Represents a filter specification for filtering books by the alpha key of their title, for the alpha picker.
@@ -5,7 +5,7 @@ using System;
using System.Linq.Expressions;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Books.Specifications;
namespace Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications;
/// <summary>
/// Represents a filter specification for filtering or searching book entities based on a search term.
@@ -0,0 +1,269 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
/// <summary>
/// Repository for albums.
/// </summary>
internal sealed class AlbumRepository : IAlbumRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="AlbumRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public AlbumRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new album.
/// </summary>
/// <param name="album">The album to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(AlbumEntity album, CancellationToken cancellationToken)
{
bool doesAlbumExist = await _luminaDbContext.Albums.AnyAsync(repositoryAlbum => repositoryAlbum.Id == album.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesAlbumExist)
return Errors.Music.AlbumAlreadyExists;
// Fetch the tags and genres referenced anywhere in the aggregate, so that the shared tables are not duplicated.
List<string> tagNames = [.. album.Tags.Select(tag => tag.Name!)
.Concat(album.Tracks.SelectMany(track => track.Tags.Select(tag => tag.Name!)))
.Distinct()];
List<string> genreNames = [.. album.Genres.Select(genre => genre.Name!)
.Concat(album.Tracks.SelectMany(track => track.Genres.Select(genre => genre.Name!)))
.Distinct()];
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);
// Replace the tags and genres of the album and of its tracks with the existing ones, so that the shared tables are not duplicated.
album.Tags = [.. album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
album.Genres = [.. album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
foreach (TrackEntity track in album.Tracks)
{
track.Tags = [.. track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
track.Genres = [.. track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
}
_luminaDbContext.Albums.Add(album);
return Result.Created;
}
/// <summary>
/// Updates an existing album, replacing its editable data while preserving its identity and audit columns.
/// </summary>
/// <param name="album">The album whose editable data is applied to the stored album.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> UpdateAsync(AlbumEntity album, CancellationToken cancellationToken)
{
AlbumEntity? foundAlbum = await _luminaDbContext.Albums
.Include(repositoryAlbum => repositoryAlbum.Tags)
.Include(repositoryAlbum => repositoryAlbum.Genres)
.Include(repositoryAlbum => repositoryAlbum.Contributors)
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == album.Id, cancellationToken).ConfigureAwait(false);
if (foundAlbum is null)
return Errors.Music.AlbumNotFound;
// The stored identity and audit columns are never overwritten by an edit.
Guid artistId = foundAlbum.ArtistId;
Guid libraryId = foundAlbum.LibraryId;
DateTime createdOnUtc = foundAlbum.CreatedOnUtc;
Guid createdBy = foundAlbum.CreatedBy;
// Copy the editable scalar properties of the album, ignoring the unchanged collection columns.
_luminaDbContext.Entry(foundAlbum).CurrentValues.SetValues(album);
foundAlbum.ArtistId = artistId;
foundAlbum.LibraryId = libraryId;
foundAlbum.CreatedOnUtc = createdOnUtc;
foundAlbum.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 => album.Tags.Select(albumTag => albumTag.Name).Contains(tag.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => album.Genres.Select(albumGenre => albumGenre.Name).Contains(genre.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
foundAlbum.Tags.Clear();
foundAlbum.Tags.UnionWith(album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag));
foundAlbum.Genres.Clear();
foundAlbum.Genres.UnionWith(album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre));
// Replace the owned ratings and contributors collections of the album, so that removed entries are deleted and new entries are inserted.
foundAlbum.Ratings.Clear();
foundAlbum.Ratings.AddRange(album.Ratings);
foundAlbum.Contributors.Clear();
foundAlbum.Contributors.AddRange(album.Contributors);
return Result.Updated;
}
/// <summary>
/// Gets an album by its Id.
/// </summary>
/// <param name="id">The Id of the album to get.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the album should be loaded together with the album itself.</param>
/// <param name="shouldTrackEntities">Whether the retrieved album should be tracked by the persistence medium, so that changes to it can be saved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either an <see cref="AlbumEntity"/>, or an error.</returns>
public async Task<Result<AlbumEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
IQueryable<AlbumEntity> query = _luminaDbContext.Albums;
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(album => album.Artist)
.Include(album => album.Ratings)
.Include(album => album.Tags)
.Include(album => album.Genres)
.Include(album => album.Contributors)
.Include(album => album.Tracks)
.ThenInclude(track => track.Ratings)
.Include(album => album.Tracks)
.ThenInclude(track => track.Genres)
.Include(album => album.Tracks)
.ThenInclude(track => track.Tags)
.Include(album => album.Tracks)
.ThenInclude(track => track.Moods)
.Include(album => album.Tracks)
.ThenInclude(track => track.Isrcs)
.Include(album => album.Tracks)
.ThenInclude(track => track.Contributors)
.AsSplitQuery();
}
return await query.FirstOrDefaultAsync(album => album.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the album identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the album to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
AlbumEntity? album = await _luminaDbContext.Albums
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == id, cancellationToken).ConfigureAwait(false);
if (album is null)
return Errors.Music.AlbumNotFound;
_luminaDbContext.Albums.Remove(album);
return Result.Deleted;
}
/// <summary>
/// Gets all the albums of the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="artistId">The Id of the artist whose albums are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="AlbumEntity"/>, or an error.</returns>
public async Task<Result<IReadOnlyList<AlbumEntity>>> GetByArtistIdAsync(Guid artistId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Albums
.Include(album => album.Ratings)
.Include(album => album.Tags)
.Include(album => album.Genres)
.Include(album => album.Contributors)
.Include(album => album.Tracks)
.ThenInclude(track => track.Ratings)
.Include(album => album.Tracks)
.ThenInclude(track => track.Genres)
.Include(album => album.Tracks)
.ThenInclude(track => track.Tags)
.Include(album => album.Tracks)
.ThenInclude(track => track.Moods)
.Include(album => album.Tracks)
.ThenInclude(track => track.Isrcs)
.Include(album => album.Tracks)
.ThenInclude(track => track.Contributors)
.AsSplitQuery()
.Where(album => album.ArtistId == artistId)
.OrderBy(album => album.Title)
.ThenBy(album => album.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the lightweight read models of the albums of the artist identified by <paramref name="artistId"/>,
/// or all of them when the pagination data is <see langword="null"/>, projecting only the fields needed to display the albums in a card-based grid.
/// </summary>
/// <param name="artistId">The Id of the artist whose albums are retrieved.</param>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching albums are returned.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{AlbumLiteRow}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<AlbumLiteRow>>> GetAlbumsLiteByArtistIdAsync(Guid artistId, PaginationDataDto? paginationData, CancellationToken cancellationToken)
{
// The lightweight read models are always retrieved without tracking, because they are never modified by the caller.
IQueryable<AlbumLiteRow> liteRowsQuery = _luminaDbContext.Albums
.AsNoTracking()
.Where(album => album.ArtistId == artistId)
.OrderBy(album => album.Title)
.ThenBy(album => album.Id)
.Select(album => new AlbumLiteRow
{
Id = album.Id,
Title = album.Title,
TotalTracks = album.TotalTracks
});
if (paginationData is null)
{
IReadOnlyList<AlbumLiteRow> allAlbums = await liteRowsQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<AlbumLiteRow>
{
Data = allAlbums,
CurrentPage = 1,
PerPage = allAlbums.Count,
Count = allAlbums.Count,
NumberOfPages = 1
};
}
int count = await liteRowsQuery.CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages));
IReadOnlyList<AlbumLiteRow> paginatedResult = await liteRowsQuery
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<AlbumLiteRow>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
}
@@ -0,0 +1,362 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
/// <summary>
/// Repository for artists.
/// </summary>
internal sealed class ArtistRepository : IArtistRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="ArtistRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public ArtistRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new artist.
/// </summary>
/// <param name="artist">The artist to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(ArtistEntity artist, CancellationToken cancellationToken)
{
bool doesArtistExist = await _luminaDbContext.Artists.AnyAsync(repositoryArtist => repositoryArtist.Id == artist.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesArtistExist)
return Errors.Music.ArtistAlreadyExists;
// An artist is unique within its library by its name, so the same artist can never be registered twice in the same library.
bool doesArtistNameExist = await _luminaDbContext.Artists.AnyAsync(repositoryArtist => repositoryArtist.LibraryId == artist.LibraryId && repositoryArtist.Name == artist.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesArtistNameExist)
return Errors.Music.ArtistAlreadyExists;
// Fetch the tags and genres referenced anywhere in the aggregate, so that the shared tables are not duplicated.
List<string> tagNames = [.. artist.Albums
.SelectMany(album => album.Tags.Select(tag => tag.Name!))
.Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags.Select(tag => tag.Name!))))
.Distinct()];
List<string> genreNames = [.. artist.Albums
.SelectMany(album => album.Genres.Select(genre => genre.Name!))
.Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres.Select(genre => genre.Name!))))
.Distinct()];
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);
// Replace the tags and genres of every album and track of the aggregate with the existing ones, so that the shared tables are not duplicated.
foreach (AlbumEntity album in artist.Albums)
{
album.Tags = [.. album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
album.Genres = [.. album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
foreach (TrackEntity track in album.Tracks)
{
track.Tags = [.. track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
track.Genres = [.. track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
}
}
_luminaDbContext.Artists.Add(artist);
return Result.Created;
}
/// <summary>
/// Updates an existing artist.
/// </summary>
/// <param name="artist">The artist to update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> UpdateAsync(ArtistEntity artist, CancellationToken cancellationToken)
{
ArtistEntity? foundArtist = await _luminaDbContext.Artists
.Include(repositoryArtist => repositoryArtist.Contributors)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Tracks)
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == artist.Id, cancellationToken).ConfigureAwait(false);
if (foundArtist is null)
return Errors.Music.ArtistNotFound;
// The stored identity and audit columns are never overwritten by an edit.
Guid libraryId = foundArtist.LibraryId;
DateTime createdOnUtc = foundArtist.CreatedOnUtc;
Guid createdBy = foundArtist.CreatedBy;
// Copy the editable scalar properties of the artist, ignoring the unchanged collection columns.
_luminaDbContext.Entry(foundArtist).CurrentValues.SetValues(artist);
foundArtist.LibraryId = libraryId;
foundArtist.CreatedOnUtc = createdOnUtc;
foundArtist.CreatedBy = createdBy;
// Replace the owned collections of the artist, so that removed entries are deleted and new entries are inserted.
foundArtist.Contributors.Clear();
foundArtist.Contributors.AddRange(artist.Contributors);
foundArtist.Albums.Clear();
foundArtist.Albums.AddRange(artist.Albums);
return Result.Updated;
}
/// <summary>
/// Gets an artist by its Id.
/// </summary>
/// <param name="id">The Id of the artist to get.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the artist should be loaded together with the artist itself.</param>
/// <param name="shouldTrackEntities">Whether the retrieved artist should be tracked by the persistence medium, so that changes to it can be saved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either an <see cref="ArtistEntity"/>, or an error.</returns>
public async Task<Result<ArtistEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
IQueryable<ArtistEntity> query = _luminaDbContext.Artists;
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Ratings)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Genres)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tags)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Ratings)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Genres)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Tags)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Moods)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Isrcs)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Contributors)
.AsSplitQuery();
}
return await query.FirstOrDefaultAsync(artist => artist.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the artist identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the artist to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
ArtistEntity? artist = await _luminaDbContext.Artists
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == id, cancellationToken).ConfigureAwait(false);
if (artist is null)
return Errors.Music.ArtistNotFound;
_luminaDbContext.Artists.Remove(artist);
return Result.Deleted;
}
/// <summary>
/// Gets paginated artists, or all the artists of the matching filters when the pagination data is <see langword="null"/>.
/// </summary>
/// <typeparam name="TFilter">The type of the filter used for filtering the data.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching artists are returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{ArtistEntity}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<ArtistEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
IQueryable<ArtistEntity> artistsQuery = _luminaDbContext.Artists;
if (!shouldTrackEntities)
artistsQuery = artistsQuery.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
artistsQuery = artistsQuery
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Ratings)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Genres)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tags)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Ratings)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Genres)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Tags)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Moods)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Isrcs)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Contributors)
.AsSplitQuery();
}
// Artists should always be retrieved only per owning libraries.
if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty)
return Errors.Library.FilterMustIncludeLibraryId;
artistsQuery = artistsQuery.Where(artist => artist.LibraryId == libraryFilter.LibraryId);
if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm))
artistsQuery = artistsQuery.Where(artist => artist.Name.ToLower().Contains(libraryFilter.SearchTerm.ToLower()));
IQueryable<ArtistEntity> orderedArtistsQuery = artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id);
// If no pagination was requested, return all the artists of the library.
if (paginationData is null)
{
IReadOnlyList<ArtistEntity> allArtists = await orderedArtistsQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<ArtistEntity>
{
Data = allArtists,
CurrentPage = 1,
PerPage = allArtists.Count,
Count = allArtists.Count,
NumberOfPages = 1
};
}
int count = await orderedArtistsQuery.Select(artist => artist.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages));
// Apply pagination.
IReadOnlyList<ArtistEntity> paginatedResult = await orderedArtistsQuery
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<ArtistEntity>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Gets paginated lightweight read models of the artists of the media library identified by the provided <paramref name="filterModel"/>,
/// or all of them when the pagination data is <see langword="null"/>, projecting only the fields needed to display the artists in a card-based grid.
/// </summary>
/// <typeparam name="TFilter">The type of the filter used for filtering the data.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching artists are returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{ArtistLiteRow}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<ArtistLiteRow>>> GetAllLiteAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
// Artists should always be retrieved only per owning libraries.
if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty)
return Errors.Library.FilterMustIncludeLibraryId;
// The lightweight read models are retrieved without tracking by default, because they are never modified by the caller.
IQueryable<ArtistEntity> artistsQuery = _luminaDbContext.Artists;
if (!shouldTrackEntities)
artistsQuery = artistsQuery.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
artistsQuery = artistsQuery
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums);
}
artistsQuery = artistsQuery.Where(artist => artist.LibraryId == libraryFilter.LibraryId);
if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm))
artistsQuery = artistsQuery.Where(artist => artist.Name.ToLower().Contains(libraryFilter.SearchTerm.ToLower()));
IQueryable<ArtistLiteRow> liteRowsQuery = artistsQuery
.OrderBy(artist => artist.Name)
.ThenBy(artist => artist.Id)
.Select(artist => new ArtistLiteRow
{
Id = artist.Id,
Name = artist.Name
});
// If no pagination was requested, return all the artists of the library.
if (paginationData is null)
{
IReadOnlyList<ArtistLiteRow> allArtists = await liteRowsQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<ArtistLiteRow>
{
Data = allArtists,
CurrentPage = 1,
PerPage = allArtists.Count,
Count = allArtists.Count,
NumberOfPages = 1
};
}
int count = await artistsQuery.Select(artist => artist.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages));
// Apply pagination.
IReadOnlyList<ArtistLiteRow> paginatedResult = await liteRowsQuery
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<ArtistLiteRow>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
}
@@ -0,0 +1,247 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
/// <summary>
/// Repository for tracks.
/// </summary>
internal sealed class TrackRepository : ITrackRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="TrackRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public TrackRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new track.
/// </summary>
/// <param name="track">The track to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(TrackEntity track, CancellationToken cancellationToken)
{
bool doesTrackExist = await _luminaDbContext.Tracks.AnyAsync(repositoryTrack => repositoryTrack.Id == track.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesTrackExist)
return Errors.Music.TrackAlreadyExists;
// A track is unique within its library by its file system path, so the same file can never be registered twice in the same library.
bool doesTrackPathExist = await _luminaDbContext.Tracks.AnyAsync(repositoryTrack => repositoryTrack.LibraryId == track.LibraryId && repositoryTrack.Path == track.Path, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesTrackPathExist)
return Errors.Music.TrackAlreadyExists;
// Fetch existing tags and genres.
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(tag => track.Tags.Select(trackTag => trackTag.Name).Contains(tag.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => track.Genres.Select(trackGenre => trackGenre.Name).Contains(genre.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
// Replace tags and genres in the track with existing ones, so that the shared tables are not duplicated.
track.Tags = [.. track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
track.Genres = [.. track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
_luminaDbContext.Tracks.Add(track);
return Result.Created;
}
/// <summary>
/// Updates an existing track, replacing its editable data while preserving its identity and audit columns.
/// </summary>
/// <param name="track">The track whose editable data is applied to the stored track.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> UpdateAsync(TrackEntity track, CancellationToken cancellationToken)
{
TrackEntity? foundTrack = await _luminaDbContext.Tracks
.Include(repositoryTrack => repositoryTrack.Tags)
.Include(repositoryTrack => repositoryTrack.Genres)
.Include(repositoryTrack => repositoryTrack.Contributors)
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == track.Id, cancellationToken).ConfigureAwait(false);
if (foundTrack is null)
return Errors.Music.TrackNotFound;
// The stored identity and audit columns are never overwritten by an edit.
Guid albumId = foundTrack.AlbumId;
Guid libraryId = foundTrack.LibraryId;
DateTime createdOnUtc = foundTrack.CreatedOnUtc;
Guid createdBy = foundTrack.CreatedBy;
// Copy the editable scalar properties of the track, ignoring the unchanged collection columns.
_luminaDbContext.Entry(foundTrack).CurrentValues.SetValues(track);
foundTrack.AlbumId = albumId;
foundTrack.LibraryId = libraryId;
foundTrack.CreatedOnUtc = createdOnUtc;
foundTrack.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 => track.Tags.Select(trackTag => trackTag.Name).Contains(tag.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => track.Genres.Select(trackGenre => trackGenre.Name).Contains(genre.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
foundTrack.Tags.Clear();
foundTrack.Tags.UnionWith(track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag));
foundTrack.Genres.Clear();
foundTrack.Genres.UnionWith(track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre));
// Replace the owned collections of the track, so that removed entries are deleted and new entries are inserted.
foundTrack.Ratings.Clear();
foundTrack.Ratings.AddRange(track.Ratings);
foundTrack.Contributors.Clear();
foundTrack.Contributors.AddRange(track.Contributors);
foundTrack.Moods.Clear();
foundTrack.Moods.AddRange(track.Moods);
foundTrack.Isrcs.Clear();
foundTrack.Isrcs.AddRange(track.Isrcs);
return Result.Updated;
}
/// <summary>
/// Gets a track by its Id.
/// </summary>
/// <param name="id">The Id of the track to get.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the track should be loaded together with the track itself.</param>
/// <param name="shouldTrackEntities">Whether the retrieved track should be tracked by the persistence medium, so that changes to it can be saved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="TrackEntity"/>, or an error.</returns>
public async Task<Result<TrackEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
IQueryable<TrackEntity> query = _luminaDbContext.Tracks;
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(track => track.Album)
.ThenInclude(album => album!.Artist)
.Include(track => track.Ratings)
.Include(track => track.Tags)
.Include(track => track.Genres)
.Include(track => track.Moods)
.Include(track => track.Isrcs)
.Include(track => track.Contributors);
}
return await query.FirstOrDefaultAsync(track => track.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the track identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the track to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
TrackEntity? track = await _luminaDbContext.Tracks
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == id, cancellationToken).ConfigureAwait(false);
if (track is null)
return Errors.Music.TrackNotFound;
_luminaDbContext.Tracks.Remove(track);
return Result.Deleted;
}
/// <summary>
/// Gets all the tracks of the album identified by <paramref name="albumId"/>.
/// </summary>
/// <param name="albumId">The Id of the album whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="TrackEntity"/>, or an error.</returns>
public async Task<Result<IReadOnlyList<TrackEntity>>> GetByAlbumIdAsync(Guid albumId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Tracks
.Include(track => track.Ratings)
.Include(track => track.Tags)
.Include(track => track.Genres)
.Include(track => track.Moods)
.Include(track => track.Isrcs)
.Include(track => track.Contributors)
.Where(track => track.AlbumId == albumId)
.OrderBy(track => track.DiscNumber)
.ThenBy(track => track.TrackNumber)
.ThenBy(track => track.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the lightweight read models of the tracks of the album identified by <paramref name="albumId"/>,
/// or all of them when the pagination data is <see langword="null"/>, projecting only the fields needed to display the tracks of an album.
/// </summary>
/// <param name="albumId">The Id of the album whose tracks are retrieved.</param>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching tracks are returned.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{TrackLiteRow}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<TrackLiteRow>>> GetTracksLiteByAlbumIdAsync(Guid albumId, PaginationDataDto? paginationData, CancellationToken cancellationToken)
{
// The lightweight read models are always retrieved without tracking, because they are never modified by the caller.
IQueryable<TrackLiteRow> liteRowsQuery = _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.AlbumId == albumId)
.OrderBy(track => track.DiscNumber)
.ThenBy(track => track.TrackNumber)
.ThenBy(track => track.Id)
.Select(track => new TrackLiteRow
{
Id = track.Id,
Title = track.Title,
TrackNumber = track.TrackNumber,
DiscNumber = track.DiscNumber
});
if (paginationData is null)
{
IReadOnlyList<TrackLiteRow> allTracks = await liteRowsQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<TrackLiteRow>
{
Data = allTracks,
CurrentPage = 1,
PerPage = allTracks.Count,
Count = allTracks.Count,
NumberOfPages = 1
};
}
int count = await liteRowsQuery.CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages));
IReadOnlyList<TrackLiteRow> paginatedResult = await liteRowsQuery
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<TrackLiteRow>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
}