エラー CS1503
引数 2: は 'string' から 'System.FormattableString' へ変換することはできません
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");
}
}
}
以下のコンパイルエラーが発生します。
ExecuteSqlメソッドの第一引数の型は System.FormattableString
のため、文字列型string
をそのまま渡すことはできません。
文字列開始の "
の手前に $
を記述すると、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";
}
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";
}