ASP.NET Core で SQLite のデーターベースを生成する


新規プロジェクトの作成

dotnet new web -o CreateDbSample
cd CreateDbSample

SQLite パッケージの追加

  • ASP.NET で SQLite を扱うためのパッケージをインストールします。
dotnet add package Microsoft.EntityFrameworkCore.Sqlite

モデルの作成

  • 今回は商品モデルを作成します。
  • モデルはデータベースのレコード当たります。
  • プロジェクトルートにModelsフォルダを作成し、Modelsフォルダ内にProduct.csを作成します。
./Models/Product.cs
namespace CreateDbSample.Models
{
    public class Product
    {
        // ID は自動で主キー
        public int ID { get; set; }
        public string Name { get; set; }
        public int Price { get; set; }
    }
}

データベースコンテキストの作成

  • Modelsフォルダ内にShopDbContext.csを作成します。
  • このコンテキストを通して DB にアクセスします。
  • DbSet<Product>がテーブルのイメージです。
./Models/ShopDbContext.cs
using Microsoft.EntityFrameworkCore;

namespace CreateDbSample.Models
{
    public class ShopDbContext : DbContext
    {
        public ShopDbContext(DbContextOptions options)
            : base(options) { }

        public DbSet<Product> Products { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =>
            optionsBuilder.UseSqlite("Data Source=shop.db");
    }
}

Startup.csの編集

  • データベースコンテキストを DI コンテナーに登録します。
  • 後で Web API で動確するためにAddMvc UseMVCを設定します。
using CreateDbSample.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace CreateDbSample
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddDbContext<ShopDbContext>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            app.UseMvc();
            app.Run(async (context) => await context.Response.WriteAsync("Hello World!"));
        }
    }
}

データベースの生成

  • データベースの設計図となるマイグレーションファイルをスキャフォールディングします。
dotnet ef migrations add Initial
  • Migrationsが追加され、その中に<timestamp>_initial.csが追加されます。
using Microsoft.EntityFrameworkCore.Migrations;

namespace CreateDbSample.Migrations
{
    public partial class Initial : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Products",
                columns: table => new
                {
                    ID = table.Column<int>(nullable: false)
                        .Annotation("Sqlite:Autoincrement", true),
                    Name = table.Column<string>(nullable: true),
                    Price = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Products", x => x.ID);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Products");
        }
    }
}

  • データベースを生成するため、以下のコマンドを入力します。
dotnet ef database update

プロジェクトのルートフォルダにshop.dbが追加されます。


Web API で動作確認

  • Controllers/productsController.csを作成します。
  • 商品追加と商品一覧取得のメソッドを持ちます。
using CreateDbSample.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

namespace CreateDbSample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        ShopDbContext Context { get; set; }
        public ProductsController(ShopDbContext context)
        {
            Context = context;
        }

        [HttpPost]
        public Product AddProduct(Product product)
        {
            Context.Products.Add(product);
            Context.SaveChanges();
            return product;
        }

        [HttpGet]
        public IEnumerable<Product> GetProducts() => Context.Products.ToList();
    }
}

dotnet runしてサーバーを立ち上げます。
POSTMAN で動作確認します。

  • 追加

  • 一覧取得

SQLite のデータベースが動いていることが確認できました!