我尝试了几种方法来通过 C# 运行我的 Model-First Entity Designer SQL 文件,但没有运气。我有一个 SQL 文件,其中包含我加载和读取的所有代码。
下面是我的代码。它在执行的每个命令上都会出错。请注意,我正在通过我的模型容器的连接属性检索连接,该属性的类型为DbConnection
,但我不确定这是否与它有关。
C#脚本:
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();
收到错误。我收到的一些错误如下:
错误一:
IF OBJECT_ID(N'[dbo].[FK_UserStory]', 'F') IS NOT NULL
ALTER TABLE [dbo].[StorySet] DROP CONSTRAINT [FK_UserStory];
查询语法无效。靠近标识符“OBJECT_ID”,第 1 行,第 4 列。
错误2:
IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]');
查询语法无效。靠近标识符“SCHEMA_ID”,第 1 行,第 4 列。