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?

【保険商品管理システムの開発】生命保険のコントローラーをSQLiteに接続する修正

Posted at

1. DbContext(AppDbContext)の利用

Controllers/LifeInsuranceController.cs
private readonly AppDbContext _context;

public LifeInsuranceController(AppDbContext context)
{
    _context = context;
}

1) private readonly AppDbContext _context;

• AppDbContext
EF Core の DbContext を継承したあなたのデータアクセス用クラス。
ここに DbSet などがあり、_context.Customers のようにしてDBにアクセスします。

2) public LifeInsuranceController(AppDbContext context)

• 引数 AppDbContext context
ここが**依存性注入(DI)**の入口。Program.cs で

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));

と登録しているため、ASP.NET Core がリクエストごと(Scoped)に AppDbContext を作って自動で渡してくれる仕組みです。

3) { _context = context; }

• 受け取った context(コンストラクター引数のローカル)を、クラスのフィールド _context に一度だけ代入して保持します。
• これで、アクションメソッドの中で

_context.Customers.Add(...);
await _context.SaveChangesAsync();

のように DB 操作ができるようになります。

2. 顧客データの登録(INSERT)

Controllers/LifeInsuranceController.cs
_context.Customers.Add(customer);
await _context.SaveChangesAsync();

• InsurancePolicies テーブルに新しい契約を保存。
• SaveChangesAsync() が呼ばれるとSQLiteにデータが永続化される。

3. 保険契約データの登録(INSERT)

Controllers/LifeInsuranceController.cs
_context.InsurancePolicies.Add(policy);
await _context.SaveChangesAsync();

4. 有効契約の取得(SELECT + 条件)

Controllers/LifeInsuranceController.cs
var activePolicies = await _context.InsurancePolicies
    .Where(p => p.CustomerId == customerId && p.IsActive && !p.IsExpired())
    .ToListAsync();

• Where(...) で、Models/InsurancePolicy.csの顧客ID・有効フラグ・期限切れでないことを条件に検索。
• ToListAsync() が呼ばれると実際にSQLiteに対して SELECT クエリが発行される。

5. 保険料合計の計算(SELECT + SUM)

Controllers/LifeInsuranceController.cs
var totalPremium = await _context.InsurancePolicies
    .Where(p => p.CustomerId == customerId && p.IsActive && !p.IsExpired())
    .SumAsync(p => p.Premium);

• 条件に合致した契約の Premium 列の合計を取得。
• 実際にはSQLiteに対して SELECT SUM(Premium) が発行される。

6. 保険金請求(UPDATE)

Controllers/LifeInsuranceController.cs
var policy = await _context.InsurancePolicies
    .FirstOrDefaultAsync(p => p.PolicyId == policyId);

policy.IsActive = false;
await _context.SaveChangesAsync();

• PolicyIdで特定の契約を検索し、IsActive を false に変更。
• SaveChangesAsync() 実行時に UPDATE が発行される。

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?