ASP.NET MVCでEntityFrameworkを試す

C# コンピュータ
C#
ASP.NET MVCを勉強中なのですが進捗状況はあまりかんばしく無いです。
特にデータベースにアクセスをMVCへ落とし込む方法が知りたいので、msdnのチュートリアルを写経して、大まかな構成を理解できないかと試してみたいと思います。
チュートリアル: ASP.NET MVC Web アプリでの EF Core の概要
このページは、Contoso University のサンプル EF/MVC アプリを作成する方法を説明するチュートリアル シリーズの 1 回目です

msdnのチュートリアルではSQL Serverを利用するようになっていますが、データベースを用意するのが面倒なので、データベースはSQLiteにします。

プロジェクトの作成

mkdir プロジェクト名
cd プロジェクト名
dotnet new mvc
dotnet add package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore -v 5.0.0
dotnet add package Microsoft.EntityFrameworkCore.Sqlite -v 5.0.0
dotnet add package Microsoft.EntityFrameworkCore.Tools -v 5.0.0
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design -v 5.0.0
プロジェクトファイルを覗いてみる。
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="5.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.0" />
  </ItemGroup>

</Project>
.Netの最新は6らしく自分が実行している環境は.Netの5なのでパッケージを追加する際-vでバージョンを指定してあげる必要がありました。

Modelとコンテキストを作成

ModelsにPersonクラスを作成

using System;
using System.Collections.Generic;

namespace ContactList.Models
{
    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}
このクラスがEntityと言うものらしいのですが、大まかな構成を知るために1つだけ用意します。
多分データベースのテーブルと紐づくと思われます。

Dataフォルダを作成しContactListContextクラスを作成

using ContactList.Models;
using Microsoft.EntityFrameworkCore;

namespace ContactList.Data
{
    public class ContactListContext : DbContext
    {
        public ContactListContext(DbContextOptions<ContactListContext> options) : base(options)
        {
        }
        public DbSet<Person> Persons { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Person>().ToTable("Person");
        }
    }
}
こちらのクラスを介して実際のデータベースからデータを取り出したりセットしたりすると思われます。

Startup.csにコンテキストの登録

using ContactList.Data; // 追加
using Microsoft.EntityFrameworkCore; // 追加
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ContactList
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ContactListContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); // 追加
            services.AddDatabaseDeveloperPageExceptionFilter(); // 追加

            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
チュートリアルではoptions.UseSqlServerとなっていますがSQLiteを使いたいのでoptions.UseSqliteとしています。
またConfiguration.GetConnectionString(“DefaultConnection”)を引数にしていますので、こちらがデータベースの接続文字列だと思われます。

appsettings.jsonに接続文字列をセット

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source = C:/Users/karet/source/repos/ContactList/Sample.db"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
接続文字列をSQLite用にしています。Data Srouceにデータベースファイルのパスを指定するシンプルな形で動いてくれます。
後々を考えるとデータベースファイルは相対パスで記述したいところですが、どこにファイルが出来上がるか不明ですので絶対パスで記述しています。

DataフォルダにDbInitializerクラスを作成する

using ContactList.Models;
using System;
using System.Linq;

namespace ContactList.Data
{
    public static class DbInitializer
    {
        public static void Initialize(ContactListContext context)
        {
            context.Database.EnsureCreated();

            if (context.Persons.Any())
            {
                return;   // DB has been seeded
            }

            var persons = new Person[]
            {
            new Person{ID=1, Name="Taro"},
            new Person{ID=2, Name="Jiro"},
            new Person{ID=3, Name="Hanako"},
            };
            foreach (var s in persons)
            {
                context.Persons.Add(s);
            }
            context.SaveChanges();
        }
    }
}
テーブルが存在していない場合テーブルを作成し、テーブルが空の場合レコードを追加しているように見受けられます。

Program.csを変更する

using ContactList.Data; // 追加
using Microsoft.Extensions.DependencyInjection; // 追加
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace ContactList
{
    public class Program
    {
        public static void Main(string[] args) // 変更
        {
            var host = CreateHostBuilder(args).Build();

            CreateDbIfNotExists(host);

            host.Run();
        }
        private static void CreateDbIfNotExists(IHost host) // 追加
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<ContactListContext>();
                    DbInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred creating the DB.");
                }
            }
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}
DbInitializerを呼び出しています。

実行してみる

ここまでmsdnのチュートリアルを進めてきましたが、これ以降はVisualStudioを使った作業となりますので、dotnet.exeとVSCodeを使っている関係でこのまま進めることが出来ません。とは言えここまでのプログラムでデータベースを作成はしてくれそうなので、とりあえずこの辺りでF5キーを押してデバッグ実行してみます。

実行したところEdgeが起動しMVCで出来たページが表示されました。データソースで指定したデータベースファイルが出来上がっていたので、思った通りに動いてくれました。

ビューとコントローラーを作成する

Controllers/PersonsController.csを作成

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ContactList.Data;
using ContactList.Models;

namespace ContactList.Controllers
{
    public class PersonsController : Controller
    {
        private readonly ContactListContext _context;

        public PersonsController(ContactListContext context)
        {
            _context = context;
        }

        // GET: Persons
        public async Task<IActionResult> Index()
        {
            return View(await _context.Persons.ToListAsync());
        }

        // GET: Persons/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = await _context.Persons
                .FirstOrDefaultAsync(m => m.ID == id);
            if (person == null)
            {
                return NotFound();
            }

            return View(person);
        }

        // GET: Persons/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Persons/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ID,Name")] Person person)
        {
            if (ModelState.IsValid)
            {
                _context.Add(person);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(person);
        }

        // GET: Persons/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = await _context.Persons.FindAsync(id);
            if (person == null)
            {
                return NotFound();
            }
            return View(person);
        }

        // POST: Persons/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,Name")] Person person)
        {
            if (id != person.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(person);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PersonExists(person.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(person);
        }

        // GET: Persons/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = await _context.Persons
                .FirstOrDefaultAsync(m => m.ID == id);
            if (person == null)
            {
                return NotFound();
            }

            return View(person);
        }

        // POST: Persons/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var person = await _context.Persons.FindAsync(id);
            _context.Persons.Remove(person);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool PersonExists(int id)
        {
            return _context.Persons.Any(e => e.ID == id);
        }
    }
}

Views/Shared/_Layout.cshtmlを変更

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - ContactList</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">ContactList</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Persons" asp-action="Index">Persons</a> @* 変更 *@
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2021 - ContactList - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

PersonsコントローラーのIndexアクションが呼び出されるように変更します。

Views/Persons/Index.cshtmlを作成

@model IEnumerable<ContactList.Models.Person>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.ID">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

Views/Persons/Create.cshtmlを作成

 @model ContactList.Models.Person

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Student</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Views/Persons/Delete.cshtmlを作成

@model ContactList.Models.Person

@{
    ViewData["Title"] = "Delete";
}

<h1>Delete</h1>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Person</h4>
    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
    </dl>
    
    <form asp-action="Delete">
        <input type="hidden" asp-for="ID" />
        <input type="submit" value="Delete" class="btn btn-danger" /> |
        <a asp-action="Index">Back to List</a>
    </form>
</div>

Views/Persons/Details.cshtmlを作成

@model ContactList.Models.Person;

@{
    ViewData["Title"] = "Details";
}

<h1>Details</h1>

<div>
    <h4>Person</h4>
    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
    </dl>
</div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.ID">Edit</a> |
    <a asp-action="Index">Back to List</a>
</div>

Views/Persons/Edit.cshtmlを作成

@model ContactList.Models.Person

@{
    ViewData["Title"] = "Edit";
}

<h1>Edit</h1>

<h4>Person</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="ID" />
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Visual Studio 2019でmsdnのチュートリアルを実行し、出来上がったソースプログラムを参考にコントローラーとビューを作成してみました。
エンティティ(テーブル)は大分省略しましたが、VSCodeとdotnet.exeの組み合わせで動くサンプルが出来上がりました。
初めにも書きましたがチュートリアルではデータベースがSQL Server(localdb)でしたが、こちらのサンプルではSQLiteにしてみました。
特に知りたかったデータベースのアクセス部分なのですが、コンテキストクラスでデータベースとModelのEntitiyクラスを紐づけし、コントローラーのアクションでコンテキストを介してデータベースの処理を実行しているようです。テーブル追加更新などの引数や、テーブルからデータを取得する際の戻り値に相当するデータ型としてEntitiyクラスが利用されているようです。
とりあえず動くサンプルを手に入れましたので、こちらをベースにして、ASP.NET MVCの学習を進めていきたいと思います。

コメント