🐛 Another bug fix

This commit is contained in:
LittleSheep 2025-06-02 21:22:38 +08:00
parent 5487b4e607
commit 740f5ad3fc

View File

@ -34,33 +34,41 @@ public class FileReferenceMigrationService(AppDatabase db)
{ {
var posts = await db.Posts var posts = await db.Posts
.Include(p => p.OutdatedAttachments) .Include(p => p.OutdatedAttachments)
.Where(p => p.OutdatedAttachments.Any())
.ToListAsync(); .ToListAsync();
var attachmentsId = posts.SelectMany(p => p.OutdatedAttachments.Select(a => a.Id)).ToList(); var attachmentsId = posts.SelectMany(p => p.OutdatedAttachments.Select(a => a.Id)).ToList();
var attachments = await db.Files.Where(f => attachmentsId.Contains(f.Id)).ToListAsync(); var attachments =
var attachmentsDict = attachments await db.Files.Where(f => attachmentsId.Contains(f.Id)).ToDictionaryAsync(x => x.Id);
.GroupBy(a => posts.First(p => p.OutdatedAttachments.Any(oa => oa.Id == a.Id)).Id)
.ToDictionary(g => g.Key, g => g.ToList());
var fileReferences = posts.SelectMany(post => var fileReferences = posts.SelectMany(post => post.Attachments.Select(attachment =>
attachmentsDict.TryGetValue(post.Id, out var value) {
? value.Select(attachment => var value = attachments.TryGetValue(attachment.Id, out var file) ? file : null;
new CloudFileReference if (value is null) return null;
{ return new CloudFileReference
FileId = attachment.Id, {
File = attachment, FileId = value.Id,
Usage = "post", File = value,
ResourceId = post.Id.ToString(), Usage = "post",
CreatedAt = SystemClock.Instance.GetCurrentInstant(), ResourceId = post.Id.ToString(),
UpdatedAt = SystemClock.Instance.GetCurrentInstant() CreatedAt = SystemClock.Instance.GetCurrentInstant(),
}) UpdatedAt = SystemClock.Instance.GetCurrentInstant()
: [] };
) }).Where(x => x != null).Select(x => x!)
.ToList(); ).ToList();
foreach (var post in posts) foreach (var post in posts)
{ {
post.Attachments = post.OutdatedAttachments.Select(a => a.ToReferenceObject()).ToList(); var updatedAttachments = new List<CloudFileReferenceObject>();
foreach (var attachment in post.OutdatedAttachments)
{
if (await db.Files.AnyAsync(f => f.Id == attachment.Id))
updatedAttachments.Add(attachment.ToReferenceObject());
else
updatedAttachments.Add(attachment.ToReferenceObject());
}
post.Attachments = updatedAttachments;
db.Posts.Update(post); db.Posts.Update(post);
} }