動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

定石3: EF6 + Code First Migrationの最小コード

出典: ASP.NET MVC 5 で使える ORM 3択 — EF6 / Dapper / ADO.NET の業務SE 視点比較定石3: EF6 + Code First Migrationの最小コード

定石3: EF6 + Code First Migrationの最小コード (csharp)#f4027ae95f4a
// ✅定石3-b: EF6でControllerからDBアクセス
public class CustomerController : Controller
{
    private MyDbContext _db = new MyDbContext();
 
    public ActionResult Index()
    {
        var customers = _db.Customers
            .Where(c => c.Status == "active")
            .Include(c => c.Orders)// ← N+1回避のためEager Loading
            .Select(c => new CustomerVm { Id = c.Id, Name = c.Name })
            .ToList();
        return View(customers);
    }
 
    protected override void Dispose(bool disposing)
    {
        if (disposing)_db.Dispose();
        base.Dispose(disposing);
    }
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
  • id: #f4027ae95f4a
  • lines: 21
  • extracted: 2026-06-10

Source収録記事

この snippet は記事の「定石3: EF6 + Code First Migrationの最小コード」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

6
図鑑トップ