I tried several approaches to run my Model-First Entity Designer SQL file through C#, but with no luck. I have an SQL file with all the code in it which I load and read from.
Below is my code. It gives an error on every single command executed. Note that I am retrieving the connection through my Model Container's connection property which is of the type DbConnection
, but I'm not sure if that has anything to do with it.
C# script:
var commandStrings = Regex.Split(Resources.DatabaseScript, "^\\s*GO\\s*$", RegexOptions.Multiline);
//container is my EDMX container.
container.Connection.Open();
var command = container.Connection.CreateCommand();
var transaction = container.Connection.BeginTransaction();
command.Connection = container.Connection;
command.Transaction = transaction;
foreach (string commandInput in commandStrings)
{
var commandString = commandInput;
if (commandString.Trim() != "")
{
Debug.Write("Executing SQL ... ");
try
{
command.CommandText = commandString;
command.Connection = container.Connection;
command.CommandType = CommandType.Text;
command.Prepare();
command.ExecuteNonQuery();
Debug.WriteLine("Success!");
}
catch (Exception exc)
{
Debug.WriteLine("Failed!");
Debug.WriteLine("Exception: " + exc.Message);
Debug.Write("Rolling back ... ");
try
{
transaction.Rollback();
Debug.WriteLine("Success!");
} catch(Exception exce)
{
Debug.WriteLine("Exception: " + exce.Message);
}
}
finally
{
Debug.WriteLine("SQL: " + commandString);
}
}
}
transaction.Commit();
container.Connection.Close();
Errors received. Some of the errors I am receiving are as follows:
Error 1:
IF OBJECT_ID(N'[dbo].[FK_UserStory]', 'F') IS NOT NULL
ALTER TABLE [dbo].[StorySet] DROP CONSTRAINT [FK_UserStory];
The query syntax is not valid. Near identifier 'OBJECT_ID', line 1, column 4.
Error 2:
IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]');
The query syntax is not valid. Near identifier 'SCHEMA_ID', line 1, column 4.