はじめに
以前は.NET Core 3.0を使ってSQLiteのデータをWeb APIから操作してみましたが、今回は.NET 6で操作してみます。
https://qiita.com/namikitakeo/items/d98e46c2aa2cd50ee1b1
実行環境
下記バージョンで動作確認しています。
- Ubuntu 22.04
- .NET 6.0
$ dotnet --version
6.0.113
$ uname -a
Linux desktop 5.15.0-1022-raspi #24-Ubuntu SMP PREEMPT Mon Dec 5 09:58:33 UTC 2022 aarch64 aarch64 aarch64 GNU/Linux
学習方針
コマンドプロンプトから実行する事で、Mac、Windowsにおいてもそのままできると思います。
https://learn.microsoft.com/ja-jp/training/modules/build-web-api-minimal-database/
チュートリアルにしたがって以下のコードを実装します。
Models/Pizza.cs
using Microsoft.EntityFrameworkCore;
namespace PizzaStore.Models
{
public class Pizza
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
}
class PizzaDb : DbContext
{
public PizzaDb(DbContextOptions options) : base(options) { }
public DbSet<Pizza> Pizzas { get; set; } = null!;
}
}
Program.cs
app.MapGet("/", () => "Hello World!");
app.Run(); */
using PizzaStore.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("Pizzas") ?? "Data Source=Pizzas.db";
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddDbContext<PizzaDb>(options => options.UseInMemoryDatabase("items"));
builder.Services.AddSqlite<PizzaDb>(connectionString);
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {
Title = "PizzaStore API",
Description = "Making the Pizzas you love",
Version = "v1" });
});
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "PizzaStore API V1");
});
app.MapGet("/", () => "Hello World!");
app.MapPost("/pizza", async (PizzaDb db, Pizza pizza) =>
{
await db.Pizzas.AddAsync(pizza);
await db.SaveChangesAsync();
return Results.Created($"/pizza/{pizza.Id}", pizza);
});
app.MapGet("/pizza/{id}", async (PizzaDb db, int id) => await db.Pizzas.FindAsync(id));
app.MapPut("/pizza/{id}", async (PizzaDb db, Pizza updatepizza, int id) =>
{
var pizza = await db.Pizzas.FindAsync(id);
if (pizza is null) return Results.NotFound();
pizza.Name = updatepizza.Name;
pizza.Description = updatepizza.Description;
await db.SaveChangesAsync();
return Results.NoContent();
});
app.MapDelete("/pizza/{id}", async (PizzaDb db, int id) =>
{
var pizza = await db.Pizzas.FindAsync(id);
if (pizza is null)
{
return Results.NotFound();
}
db.Pizzas.Remove(pizza);
await db.SaveChangesAsync();
return Results.Ok();
});
app.MapGet("/pizzas", async (PizzaDb db) => await db.Pizzas.ToListAsync());
app.Run();