Open2

Entity FrameworkのDbContextクラスの使い方

しみゆーしみゆー

Entity Frameworkでは、検索、登録、更新、削除などの基本処理をDbContextクラスを使って行う。

しみゆーしみゆー

Postクラス

namespace PostAPI
{
    public class Post
    {
        public int Id { get; set; }
        public string Title{ get; set; } = string.Empty;
        public string Content{ get; set; } = string.Empty;
    }
}

PostContextクラス

using Microsoft.EntityFrameworkCore;

namespace PostAPI.Data
{
    public class PostContext : DbContext
    {
        public PostContext(DbContextOptions<DataContext> options): base(options)
        {
        }

        public DbSet<Post> Posts{ get; set; }
    }
}

PostController

全件取得

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PostAPI.Data;

namespace PostAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PostController : ControllerBase
    {
        private readonly PostContext _context;

        public PostController(PostContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task<ActionResult<List<Post>>> Get()
        {
            var posts = await _context.Posts.ToListAsync();
            return Ok(posts);
        }
     }
}

1件取得

        [HttpGet("{id}")]
        public async Task<ActionResult<Post>> Get(int id)
        {
            var post = await _context.Posts.FindAsync(id);
            if (post is null)
            {
                return BadRequest("Post not found.");
            }
            return Ok(post);
        }

登録

        [HttpPost]
        public async Task<ActionResult<List<Post>>> AddPost(Post post)
        {
            _context.Posts.Add(post);
            await _context.SaveChangesAsync();

            return Ok();
        }

更新

        [HttpPut]
        public async Task<ActionResult<List<Post>>> UpdatePost(Post request)
        {
            var post = await _context.Posts.FindAsync(request.Id);
            if (post is null)
            {
                return BadRequest("Post not found.");
            }
            post.Title= request.Title;
            post.Content= request.Content;

            await _context.SaveChangesAsync();

            return Ok();
        }

削除

        [HttpDelete]
        public async Task<ActionResult<List<Post>>> DeletePost(int id)
        {
            var post = await _context.Posts.FindAsync(id);
            if (post is null)
            {
                return BadRequest("Post not found.");
            }

            _context.Posts.Remove(post);
            await _context.SaveChangesAsync();

            return Ok();
        }