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?

Entity Framework を実装するには

Last updated at Posted at 2025-10-14

初めに

これは、自分の学習メモ程度です。
間違っていたりしたらすみません。

手順① DbContextを継承した自作classを作る

public class MyAppContext : DbContext{
    //ここに内容
}

手順② テーブルとのマッピング

 先ほどのclassの中に、データベース内のテーブルを表すDbSetプロパティを定義します。これにより、LINQを使ってデータを簡単に操作できます。

    public DbSet<Student> Students { get; set; }

例として、Studentテーブルの値をStudentsプロパティにマッピングする準備です

手順③ モデルの構成

例として、Studentsプロパティのモデルを作ります、実際にマッピングされる、代入先を作ります

      [Table("Student")]
  public class Students
  {
      [DisplayName("生徒名")]
      [MaxLength(50)]
      public string Name { get; set; }

      [DisplayName("性別")]
      [MaxLength(1)]
      public int Gender { get; set; }
  }

手順④ LINQを用いてDB操作

using内でのみDB操作することで、意図しないDB操作を防ぎます

    using (var context = new MyAppContext(options))
{
    // 新しいエンティティの追加
    var tanaka = new Students { Name:"田中",Gender:1};
    context.Students.Add(tanaka);

    // データベースに変更を保存
    context.SaveChanges();
}

これは、Studentテーブルにinsertする例です
entityの追加の部分を、入力値などにするといいでしょう

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?