Can Entity Framework模型可以传递一个SQL脚本来对数据库运行

Gre*_*reg 7 .net sql t-sql entity-framework

是否可以将SQL脚本传递给Entity Framework必须针对我的模型运行它的某个方法?例如相当于:

context.ExecuteStoreCommand(<tsql script path>); 
Run Code Online (Sandbox Code Playgroud)

背景:我想要一种在单元测试期间重置数据库的方法,并且调用运行EF生成的TSQL脚本(来自模型中的Generate Database)似乎是实现此目的的一种方法.

Mat*_*rts 8

我有一些简单的代码,像这样触发sql:

if (!_context.CableSweepDebug.Any(rec => /* CHECK TO SEE IF SQL ALREADY RUN */ ))
{
    var sql = System.IO.File.ReadAllText("SqlScript.sql");
    _context.Database.ExecuteSqlCommand(sql);
}
Run Code Online (Sandbox Code Playgroud)

  • 这工作得很好,除非你的 SQL 脚本包含 GO 语句或注释,这会产生语法错误。 (2认同)

Jua*_*edo 5

我找到了一个简单的方法:

  1. 将您的 SQL 脚本放入字符串变量中:

    string result = "";
    using (Stream stream = assembly.GetManifestResourceStream(resourceName))
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            result = reader.ReadToEnd();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 接下来,使用 GO 作为分隔符拆分字符串:

    string[] commands = result.Split(new string[] { "GO" }, StringSplitOptions.RemoveEmptyEntries);
    
    Run Code Online (Sandbox Code Playgroud)
  3. 最后,使用上下文中的数据库连接(包含来自/sf/answers/110545431/ 的代码)使用完全相同的顺序执行每个命令:

    YourContext context = new YourContext(); //Instance new Context
    DbConnection conn = context.Database.Connection; // Get Database connection
    ConnectionState initialState = conn.State; // Get Initial connection state
    try
    {
        if (initialState != 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 (initialState != ConnectionState.Open)
            conn.Close(); // only close connection if not initially open
    }
    
    Run Code Online (Sandbox Code Playgroud)

这就是我让它工作的方式。希望能帮助到你!


Tim*_* J. 0

不敢相信没有人回答这个问题。我现在正在想办法解决这个问题。我想您可以执行此操作的一种方法是将脚本读入字符串,然后对其执行storecommand。我想弄清楚的是这有什么限制。是否允许除 GO 之外的所有 TSQL 语句?或者您最好使用 sqlcmd.exe 来运行。这是我找到的最佳解决方案 - 使用 SMO 运行脚本:

http://social.msdn.microsoft.com/Forums/en/sqlsmoanddmo/thread/44835d6f-6bca-4374-93e2-3a0d81280781