How can I run my Entity Designer DDL Script through C#?

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.

Upvotes: 1

Views: 467

Answers (2)

I solved the issue. My code worked just fine.

But instead of using the ModelContainer's connection through container.Connection, I had to use (container.Connection as EntityConnection).StoreConnection as SqlConnection.

Upvotes: 0

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

I'm not sure what the issue may be specifically, but the order of your code where exception handling and transaction control is done is a bit odd, so I did some reworking of it below. Let me know if that makes any difference for you.

var commandStrings = Regex.Split(
    Resources.DatabaseScript,
    "^\\s*GO\\s*$",
    RegexOptions.Multiline | RegexOptions.Compiled);

// container is my EDMX container.

container.Connection.Open();
try
{
    using (var transaction = container.Connection.BeginTransaction())
    {
        try
        {
            foreach (var commandInput in commandStrings.Where(commandInput => !string.IsNullOrWhiteSpace(commandInput)))
            {
                Debug.Write("Executing SQL ... ");
                try
                {
                    using (var command = container.Connection.CreateCommand())
                    {
                        command.Connection = container.Connection;
                        command.Transaction = transaction;
                        command.CommandText = commandInput;
                        command.CommandType = CommandType.Text;
                        command.ExecuteNonQuery();
                    }

                    Debug.WriteLine("Success!");
                }
                finally
                {
                    Debug.WriteLine("SQL: " + commandInput);
                }
            }

            transaction.Commit();
        }
        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
{
    container.Connection.Close();
}

}

Upvotes: 1

Related Questions