Exemple #1
0
        public async Task <Post> AddAsync(Post post)
        {
            using (var context = new BlogPostDbContext(new DbContextOptions <BlogPostDbContext>()))
            {
                var postEntity = _mapper.Map <Post, PostEntity>(post);

                var addedPost = await context.Set <PostEntity>().AddAsync(postEntity);

                await context.SaveChangesAsync();

                return(_mapper.Map <PostEntity, Post>(addedPost.Entity));
            }
        }
Exemple #2
0
        public async Task <Comment> AddAsync(Comment entity)
        {
            using (var context = new BlogPostDbContext(new DbContextOptions <BlogPostDbContext>()))
            {
                var postExists = await context.Set <PostEntity>().AnyAsync(x => x.Id == entity.PostId);

                if (!postExists)
                {
                    throw new InvalidOperationException($"Comment can not be added. The Post {entity.PostId} can not be found.");
                }

                var commentEntity = _mapper.Map <Comment, CommentEntity>(entity);

                var addedComment = await context.Set <CommentEntity>().AddAsync(commentEntity);

                await context.SaveChangesAsync();

                return(_mapper.Map <CommentEntity, Comment>(addedComment.Entity));
            }
        }
Exemple #3
0
        public async Task <bool> RemoveAsync(Guid id)
        {
            using (var context = new BlogPostDbContext(new DbContextOptions <BlogPostDbContext>()))
            {
                var postEntity = await context.Posts
                                 .Include(pst => pst.Comments)
                                 .SingleOrDefaultAsync(pst => pst.Id == id);

                if (postEntity == null)
                {
                    throw new InvalidOperationException($"The Post Id {id} can not be found.");
                }

                if (postEntity.Comments.Count != 0)
                {
                    return(false);
                }

                context.Posts.Remove(postEntity);
                await context.SaveChangesAsync();

                return(true);
            }
        }