Entity Framework Core でテーブルを作成すると、「The entity type '(テーブル名)' requires a primary key to be defined.」 エラーが発生する - C#

Entity Framework Core でテーブルを作成すると、「The entity type '(テーブル名)' requires a primary key to be defined.」 エラーが発生する現象について紹介します。

再現プログラム

UI

下図のフォームを作成します。

コード

MyDbContext.cs
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

namespace EntityFrameworkCoreCreateTableSqlServer
{
  public class MyDbContext : DbContext
  {
    public DbSet<MyOptionData> MyTableX { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
      options.UseSqlServer("Data Source=(DBホスト名またはIPアドレス);Initial Catalog=iPentecSandBox3;User ID=(ユーザーID);Password=(パスワード);Encrypt=False");
    }
  }
}

MyOptionData.cs
using System;

namespace EntityFrameworkCoreCreateTableSqlServer
{
  public class MyOptionData
  {
    public int ProdcutCode { get; set; }
    public int StockCount { get; set; }
    public string Memo { get; set; }
    public bool Important { get; set; }
  }
}
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;

namespace EntityFrameworkCoreCreateTableSqlServer
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      MyDbContext mc = new MyDbContext();
      RelationalDatabaseCreator rdc = (RelationalDatabaseCreator)mc.Database.GetService<IDatabaseCreator>();
      rdc.CreateTables();

      textBox1.Text += "テーブルを作成しました。\r\n";
    }
  }
}

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[Create Table]ボタンをクリックすると、下記の例外が発生します。
エラーメッセージ
System.InvalidOperationException
  HResult=0x80131509
  Message=The entity type 'MyOptionData' requires a primary key to be defined.
 If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'.
 For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.
  Source=Microsoft.EntityFrameworkCore

原因

モデルのクラスのメンバに主キーの定義が無いためです。

対処法1: idプロパティを宣言する

モデルのクラスに idプロパティを宣言すると主キーとして自動認識されます。
MyOptionDataクラスのコードを以下のコードに変更します。
  public class MyOptionData
  {
    public int id { get; set; }
    public int ProdcutCode { get; set; }
    public int StockCount { get; set; }
    public string Memo { get; set; }
    public bool Important { get; set; }
  }

実行するとid列が主キーでテーブルが作成されます。

対処法2: key属性を追記する

主キーに設定するメンバにKey属性を記述します。
MyOptionDataクラスのコードを以下のコードに変更します。
  public class MyOptionData
  {
    [Key]
    public int ProdcutCode { get; set; }
    public int StockCount { get; set; }
    public string Memo { get; set; }
    public bool Important { get; set; }
  }

実行するとProductCode列が主キーでテーブルが作成されます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2022-11-28
作成日: 2022-11-27
iPentec all rights reserverd.