Ejemplo n.º 1
0
        public async Task <ImagePost> Update(int id, string description, IEnumerable <Tag> tags)
        {
            using (ShowNTellDbContext context = _contextFactory.CreateDbContext())
            {
                ImagePost storedImagePost = await context.ImagePosts
                                            .Include(p => p.Tags)
                                            .ThenInclude(t => t.Tag)
                                            .FirstOrDefaultAsync(p => p.Id == id);

                if (storedImagePost == null)
                {
                    throw new EntityNotFoundException <int>(id);
                }

                // Update the description.
                storedImagePost.Description = description;

                // Update the tags.
                ICollection <ImagePostTag> mergedTags = null;
                if (tags != null)
                {
                    // Remove all old tags.
                    context.Set <ImagePostTag>().RemoveRange(storedImagePost.Tags);

                    // Set the new tags.
                    mergedTags = await GetMergedNewAndExistingTagsFromContext(tags, context);

                    storedImagePost.Tags = ConvertImagePostTagsForSave(mergedTags);
                }

                context.Update(storedImagePost);
                await context.SaveChangesAsync();

                // Set the tags to the fully populated tags.
                if (mergedTags != null)
                {
                    storedImagePost.Tags = mergedTags;
                }

                return(storedImagePost);
            }
        }