0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【保険商品管理システムの開発】AppDbContext.csの解説

Posted at

AppDbContext クラス

Entity Framework Core を使ってアプリとデータベースを接続・操作するための中心的な役割を果たします。

• モデルとテーブルのマッピング
• 構成のカスタマイズ
• データベース接続設定の受け取り

などが行われます。これにより、アプリの中で LINQ クエリや Add, Update, Remove, Find などの便利な操作が可能になります。

AppDbContext.cs
using Microsoft.EntityFrameworkCore;

• Entity Framework Core(EF Core) の名前空間をインポートします。
• EF Core は、データベースとオブジェクト指向コード(C# クラス)をマッピングする ORM(Object-Relational Mapper)です。

AppDbContext.cs
using InsuranceProductManager.Models;

• アプリ内の Models フォルダ(または名前空間)にある InsuranceProduct モデルを使えるようにします。

AppDbContext.cs
namespace InsuranceProductManager

• このファイルのクラスが属する名前空間を定義しています。アプリの他のコードと論理的に区切るためのものです。

AppDbContext.cs
public class AppDbContext : DbContext

• AppDbContext は データベース接続を管理するクラス。
• DbContext を継承することで、EF Core の機能を利用できます。
• EF Coreとは、SQLを直接記述することなく、C# のオブジェクトを使ってデータベースを操作できるようにします。

AppDbContext.cs
public AppDbContext(DbContextOptions<AppDbContext> options)
    : base(options)

• コンストラクタです。
• DI(依存性注入)を使って DbContextOptions を渡し、ベースクラス DbContext に渡しています。
• これにより、アプリ起動時の設定(例:SQLite、SQL Server などの接続文字列)を使って DB に接続できるようになります。

AppDbContext.cs
public DbSet<InsuranceProduct> InsuranceProducts { get; set; }

• InsuranceProduct エンティティ(モデル)を、データベースの「テーブル」として扱うためのプロパティです。
• このプロパティによって、InsuranceProducts テーブルに対する CRUD操作(作成・読み取り・更新・削除) が可能になります。

AppDbContext.cs
protected override void OnModelCreating(ModelBuilder modelBuilder)

• DbContext の振る舞いをカスタマイズするメソッドです。
• エンティティごとの制約や構成(制約、キー、桁数など)をここで定義できます。

AppDbContext.cs
base.OnModelCreating(modelBuilder);

• 親クラスの処理を呼び出しており、EF Core のデフォルトの構成も維持します。

AppDbContext.cs
modelBuilder.Entity<InsuranceProduct>(entity =>

• InsuranceProduct モデルに関する個別の設定を始めています。

AppDbContext.cs
entity.HasKey(e => e.Id);

• プライマリキー(主キー)を Id に設定します。

AppDbContext.cs
entity.Property(e => e.Name).IsRequired().HasMaxLength(100);

• Name プロパティは必須項目(null 不可)で、最大長は 100 文字。

AppDbContext.cs
entity.Property(e => e.Description).HasMaxLength(500);

• Description プロパティは最大 500 文字。必須とは書いてないので null 可。

AppDbContext.cs
entity.Property(e => e.Price).HasColumnType("decimal(18,2)");

• Price プロパティは 小数点以下2桁の精度を持つ金額として保存。
• SQL Server 等では decimal(18,2) 型になります(18桁中2桁が小数)。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?