public async Task UpdateAsync(long id, BookRequestDto dto) { dto.Sanitize(); var book = await _bookRepository.GetByIdAsync(id, q => q.Include(x => x.BookTags).Include(x => x.Links)); Mapper.Map(dto, book); // 处理标签,先移除标签与图书的关联再添加 Context.RemoveRange(book.BookTags); foreach (var tname in dto.Tags) { var tag = await _tagRepository.GetByName(tname); if (tag == null) { tag = new Tag() { Name = tname } } ; book.BookTags.Add(new BookTag { Book = book, Tag = tag }); } // 处理下载链接,移除已删除项 var oldLinks = await _linkRepository.GetByBookIdAsync(id); foreach (var oldLink in oldLinks) { if (!book.Links.Any(x => x.Id == oldLink.Id)) { Context.Remove(oldLink); } } await Context.SaveChangesAsync(); }