ExecuteSql メソッドに文字列のSQL文を与えると「'string' から 'System.FormattableString' へ変換することはできません」 エラーが発生する - C#

ExecuteSql メソッドに文字列のSQL文を与えると「'string' から 'System.FormattableString' へ変換することはできません」 エラーが発生する現象の紹介です。

現象の確認

Windows Formアプリケーションを作成し、 次のコードをコンパイルするとエラーになります。
using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreOperateTableSqlServer
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
 
    private void button5_Click(object sender, EventArgs e)
    {
      MyDbContext cx = new MyDbContext();
      cx.Database.ExecuteSql("DROP TABLE MyTable1");
      textBox1.Text += "SQLを実行しました。\r\n";
    }

  }
}

MyDbContext のコードは以下です。
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

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


以下のコンパイルエラーが発生します。
エラーメッセージ
エラー CS1503
引数 2: は 'string' から 'System.FormattableString' へ変換することはできません

原因

ExecuteSqlメソッドの第一引数の型は System.FormattableString のため、文字列型stringをそのまま渡すことはできません。

対処法1 : ダブルクォーテーションの前に$を記述する

文字列開始の " の手前に $ を記述すると、FormattableString になり、ExecuteSqlメソッドに渡せます。
以下のコードであれば、ビルドが通ります。
    private void button5_Click(object sender, EventArgs e)
    {
      MyDbContext cx = new MyDbContext();
      cx.Database.ExecuteSql($"DROP TABLE MyTable1");
      textBox1.Text += "SQLを実行しました。\r\n";
    }

対処法2 : FormattableStringFactory を利用してstringを変換する

string型の文字列が用意されており、その文字列を利用したい場合は、FormattableStringFactory クラスを利用して、string型を FormattableStringオブジェクトに変換します。
 private void button5_Click(object sender, EventArgs e)
    {
      MyDbContext cx = new MyDbContext();

      cx.Database.ExecuteSql(FormattableStringFactory.Create("DROP TABLE MyTable1") );

      textBox1.Text += "SQLを実行しました。\r\n";
    }
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2022-11-27
作成日: 2022-11-27
iPentec all rights reserverd.