ASP.NET CoreでMySQLを使ってみる -Entiy Frameworkその1

はじめに

今回は、Entiy Framework Coreを使ってデータのやり取りをいい感じにしてみます。

実装

基本的には、こちらのドキュメントに従っていけばOKです。
docs.microsoft.com
なお、今回は新しくASP.NETCoreMySQLSampleという名前でプロジェクトを作成しました。

パッケージインストール

以下のコマンドを実行し、パッケージをインストールします。

$ dotnet add package Microsoft.EntityFrameworkCore
$ dotnet add package Pomelo.EntityFrameworkCore.MySql

モデルの追加

Modelsという名前でフォルダを作成し、その中に以下のUser.csを作成します。

using System;
using System.ComponentModel.DataAnnotations;

namespace ASP.NETCoreMySQLSample.Models
{
    public class User
    {
        public int ID { get; set; }
        public string name { get; set; }
    }
}

データベースコンテキストクラスの追加

Dataという名前でフォルダを作成し、その中に以下のUserContext.csを作成します。

using Microsoft.EntityFrameworkCore;

namespace ASP.NETCoreMySQLSample.Data
{
    public class UserContext : DbContext
    {
        public UserContext(DbContextOptions<UserContext> options) : base(options)
        {

        }
        public DbSet<ASP.NETCoreMySQLSample.Models.User> User { get; set; }
    }
}

設定ファイルに接続文字列を追記

appsettings.jsonAllowedHostsの下に、以下のようにDB接続文字列を追記します。

  "ConnectionStrings": {
    "UserContext": "server=127.0.0.1;port=43306;user=root;password=mysql;Database=aspdotnet"
  }

パッケージとツールのインストール

以下のコマンドを実行して、パッケージとEntity Frameworkのツールをインストールします。
<UserName>は自分の環境のものに置き換えてください

$ dotnet tool install --global dotnet-ef
$ dotnet tool install --global dotnet-aspnet-codegenerator
$ export PATH="$PATH:/Users/<UserName>/.dotnet/tools"
$ dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
$ dotnet add package Microsoft.EntityFrameworkCore.Design
$ dotnet add package Microsoft.EntityFrameworkCore.SqlServer

今回はMySQLを使うので、Microsoft.EntityFrameworkCore.SqlServerは不要かと思いましたが、どうやら必要みたいです。インストールしましょう。

データベースコンテキストの登録

Startup.csを以下のように変更します。

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;

using ASP.NETCoreMySQLSample.Data;
using Microsoft.EntityFrameworkCore;

namespace ASP.NETCoreMySQLSample
{
    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.AddRazorPages();

            services.AddDbContext<UserContext>(options =>
                options.UseMySql(Configuration.GetConnectionString("UserContext")));
        }

        // 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("/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.MapRazorPages();
            });
        }
    }
}

options.UseMySqlを追記して、MySQLに接続するようにします。

おわりに

ちょっと長くなったので、続きはASP.NET CoreでMySQLを使ってみる -Entiy Frameworkその2に書きます。