Based on Juanu answer here is a complete solution that works with Entity Frame Core 5.
I use it to setup the database before running the test.
private void SetupTestData()
{
var sql = System.IO.File.ReadAllText("SetupEntities.sql");
string[] commands = sql.Split(new string[] { "GO" }, StringSplitOptions.RemoveEmptyEntries);
DbConnection conn = _dbContext.Database.GetDbConnection(); // Get Database connection
var initialConnectionState = conn.State;
try
{
if (initialConnectionState != ConnectionState.Open)
conn.Open(); // open connection if not already open
using (DbCommand cmd = conn.CreateCommand())
{
// Iterate the string array and execute each one.
foreach (string thisCommand in commands)
{
cmd.CommandText = thisCommand;
cmd.ExecuteNonQuery();
}
}
}
finally
{
if (initialConnectionState != ConnectionState.Open)
conn.Close(); // only close connection if not initially open
}
}