Open2

EntityFrameworkCoreメモ

しみゆーしみゆー

DbContextと接続先の設定

EntityFrameworkCoreとやり取りする窓口のようなもの。
DbContextを継承して、設定等を追加して使う。

public class ApplicationDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // 接続先の設定
        var builder = new SqlConnectionStringBuilder();
        builder.DataSource = "localhost"; // 接続先のSQLServerのインスタンス(localhostやIPアドレス)
        builder.InitialCatalog = "MyDatabase"; // 使用するデータベース名
        builder.IntegratedSecurity = false; // SQL Server認証を使用する場合はfalse
        builder.UserID = "ユーザー名"; // SQL Server認証のユーザー名
        builder.Password = "パスワード"; // SQL Server認証のパスワード

        optionsBuilder.UseSqlServer(builder.ConnectionString);
    }
    // DbSetプロパティ
    // データベースのPostテーブルを表しており、このテーブルに対しての操作を可能にするプロパティ
    // Postsがテーブル名
    public DbSet<Post> Posts{ get; set; }
}

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

DbContextを使ってデータベースにアクセスする

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

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

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

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

EFCoreのログを出力したい場合

optionsBuilder.UseSqlServer(builder.ConnectionString)
              .LogTo(message => System.Diagnostics.Debug.WriteLine(message));