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?

【保険商品管理システムの開発】生命保険契約モデルの作成

Posted at

コード

Models/LifeInsurancePolicy.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace InsuranceProductManager.Models
{
    /// <summary>
    /// 生命保険契約モデル
    /// </summary>
    public class LifeInsurancePolicy
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int PolicyId { get; set; }

        [Required]
        public int CustomerId { get; set; }

        [ForeignKey(nameof(CustomerId))]
        public Customer? Customer { get; set; }

        [Required(ErrorMessage = "保険商品名は必須です。")]
        [MaxLength(100)]
        public string ProductName { get; set; } = string.Empty;

        [Required(ErrorMessage = "契約開始日は必須です。")]
        public DateTime StartDate { get; set; }

        [Required(ErrorMessage = "契約終了日は必須です。")]
        public DateTime EndDate { get; set; }

        [Required(ErrorMessage = "保険金額は必須です。")]
        [Range(100000, 100000000, ErrorMessage = "保険金額は10万円以上1億円以下で設定してください。")]
        public decimal CoverageAmount { get; set; }

        public bool IsActive { get; set; } = true;

        /// <summary>
        /// 契約期間(年数)
        /// </summary>
        public int GetContractYears()
        {
            return (EndDate.Year - StartDate.Year);
        }

        /// <summary>
        /// 契約が失効しているか
        /// </summary>
        public bool IsExpired()
        {
            return DateTime.Today > EndDate;
        }
    }
}

解説

  1. [Key]
    • このプロパティが 主キー (Primary Key) であることを示します。
    • EF Core は通常、クラス名 + Id(例: InsurancePolicyId, Id)を自動的に主キーとして推測しますが、名前が違う場合に [Key] を付けて明示します。

  2. [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    • このプロパティが データベース側で自動生成される列 であることを指定します。
    • Identity を指定すると、SQL Server や SQLite では「オートインクリメント列」として扱われます。
    • つまり、新しいレコードを追加するとき、開発者が PolicyId を手動でセットする必要はなく、DB が自動的に連番を生成してくれます。
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?