1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【保険商品管理システムの開発】コントローラーの解説

Posted at

✅ 主な目的

• データベースに保存されている保険商品(InsuranceProducts)を、ページ番号 (page) と ページサイズ (pageSize) を指定して取得するための GET API を提供します。

InsuranceProductsController.cs
using Microsoft.AspNetCore.Mvc;

▶️ ASP.NET CoreのWeb API機能を使うために必要な名前空間(ControllerBase, ApiController, Route などが含まれます)。

InsuranceProductsController.cs
using Microsoft.EntityFrameworkCore;

▶️ Entity Framework Core(EF Core)を使ってデータベースとやり取りするための名前空間。.ToListAsync()や.CountAsync()などの拡張メソッドを使うために必要です。

InsuranceProductsController.cs
using System.Threading.Tasks;

▶️ async/await 機能を使って非同期処理を書くために必要です。

InsuranceProductsController.cs
using System.Linq;

▶️ LINQ(Language Integrated Query)を使うために必要。OrderBy, Skip, Takeなどのメソッドが含まれます。

LINQとは、様々なデータソース(コレクション、データベース、XMLなど)に対して、SQLのような構文でデータを操作できる機能です。

InsuranceProductsController.cs
namespace InsuranceProductManager.Controllers

▶️ このクラスが属する名前空間を定義。プロジェクト名に合わせて整理されています。

InsuranceProductsController.cs
[Route("api/[controller]")]

▶️ コントローラーのルートURLを定義します。[controller] はこのクラス名(InsuranceProducts)から Controller を除いた文字列になります。
👉 結果的に /api/insuranceproducts がエンドポイントになります。

APIは、異なるソフトウェアアプリケーションが互いに通信するためのインターフェースであり、エンドポイントはその通信の入り口となるURLやURI (Uniform Resource Identifier) です。

InsuranceProductsController.cs
[ApiController]

▶️ APIコントローラーであることを示す属性です。バリデーションやルーティングなどの動作が強化されます。

InsuranceProductsController.cs
public class InsuranceProductsController : ControllerBase

▶️ このクラスはWeb APIのコントローラーであり、ControllerBase を継承しています(UIを持たないAPI用コントローラー)。

InsuranceProductsController.cs
private readonly AppDbContext _context;

▶️ データベースに接続するための AppDbContext のインスタンス。依存性注入(DI)で渡されます。

依存性注入(Dependency Injection、DI)とは、オブジェクトが依存する他のオブジェクトを、そのオブジェクト自身が生成するのではなく、外部から提供(注入)する設計パターンです。

InsuranceProductsController.cs
public InsuranceProductsController(AppDbContext context)

▶️ コントローラーのコンストラクタ。DIコンテナから AppDbContext が渡されるようになっています。

InsuranceProductsController.cs
_context = context;

▶️ 受け取った context をクラス内の _context に代入して保存します。

InsuranceProductsController.cs
[HttpGet]

▶️ このメソッドがHTTPの GET リクエストに対応していることを示す属性です。

InsuranceProductsController.cs
public async Task<IActionResult> GetProducts([FromQuery] int page = 1, [FromQuery] int pageSize = 10)

▶️ GETリクエスト /api/insuranceproducts?page=1&pageSize=10 などの形式でページ番号・件数を受け取って、保険商品のリストを返す非同期メソッドです。
• Task は非同期でAPIレスポンスを返す型。
• [FromQuery] はクエリパラメータから値を取得することを意味します。
• page はページ番号、pageSize は1ページあたりの件数(デフォルトは10)。

InsuranceProductsController.cs
if (page <= 0 || pageSize <= 0)
{
    return BadRequest("ページ番号とページサイズは1以上で指定してください。");
}

▶️ ページ番号やページサイズが不正な場合(1未満)は、HTTP 400 Bad Request を返します。

InsuranceProductsController.cs
var totalItems = await _context.InsuranceProducts.CountAsync();

▶️ InsuranceProducts テーブルの全アイテム数を非同期で取得します。

InsuranceProductsController.cs
var totalPages = (int)System.Math.Ceiling(totalItems / (double)pageSize);

▶️ 総ページ数を計算します。たとえば全15件で pageSize=10 なら、Math.Ceiling(15/10.0) = 2 ページになります。

InsuranceProductsController.cs
var products = await _context.InsuranceProducts
    .OrderBy(p => p.Id)
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();

▶️ データベースから保険商品をページングして取得します。
• OrderBy(p => p.Id):ID順に並べます。
• Skip(...):指定ページまでスキップ。
• Take(pageSize):指定ページ分だけ取得。
• ToListAsync():結果をリスト化して非同期で取得。

InsuranceProductsController.cs
return Ok(new
{
    totalItems,
    totalPages,
    currentPage = page,
    pageSize,
    items = products
});

▶️ 結果をJSONで返します。構造は以下のようになります:

InsuranceProductsController.cs
{
  "totalItems": 53,
  "totalPages": 6,
  "currentPage": 1,
  "pageSize": 10,
  "items": [ /* 保険商品のリスト */ ]
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?