Пример #1
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));
            }
        }
Пример #2
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));
            }
        }