2010-05-29 39 views
7

是否有可能將SQL腳本傳遞給Entity Framework必須針對我的模型運行它的某種方法?例如實體框架模型是否可以傳遞一個SQL腳本以針對數據庫運行

context.ExecuteStoreCommand(<tsql script path>); 

背景:相當於我想辦法在單元測試來重新設置數據庫,並進行呼叫運行EF生成TSQL腳本(從生成模型數據庫),似乎實現這一目標的方法之一。

+0

恕我直言:在單元測試期間不要連接到數據庫。問題解決了。 – 2010-06-01 13:14:18

+8

如果我使用術語集成而不是單位 – Greg 2010-06-02 00:05:11

回答

0

不能相信沒有人回答這個問題。我正試圖弄清楚這一點。我想你可以做到這一點的一種方法是將腳本讀入一個字符串,然後對此執行storestore命令。我想弄清楚的是這個限制是什麼。是否允許GO以外的所有TSQL語句?或者,這是你最好使用sqlcmd.exe運行。下面是我找到最好的解決辦法 - 使用SMO來運行腳本:

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

0

你爲什麼不乾脆讓SqlConnection的一個簡單的ADO.NET連接在測試環境中執行SQL對你的分貝。由於只有極少數簡單的SQL語句,您不會將您的測試部署或導出到開發場所以外的任何地方。我不認爲有必要通過實體框架來做到這一點。

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); 
} 
+1

這會工作正常,除非您的SQL腳本包含GO語句或註釋,這會給出語法錯誤。 – 2015-01-28 11:51:39

0

保持簡單

using (var context = new MyDBEntities()) 
{ 
    var m = context.ExecuteStoreQuery<MyDataObject>("Select * from Person", string.Empty); 
    //Do anything you want to do with 
    MessageBox.Show(m.Count().ToString()); 
} 
2

我發現了一個簡單的方法:

  1. 讓您的SQL腳本到一個字符串變量:

    string result = ""; 
    using (Stream stream = assembly.GetManifestResourceStream(resourceName)) 
    { 
        using (StreamReader reader = new StreamReader(stream)) 
        { 
         result = reader.ReadToEnd(); 
        } 
    } 
    
  2. 接着,分割使用GO作爲隔膜的字符串:

    string[] commands = result.Split(new string[] { "GO" }, StringSplitOptions.RemoveEmptyEntries); 
    
  3. 最後,使用完全相同的順序執行每個命令,使用從背景信息的數據庫連接(包含代碼從https://stackoverflow.com/a/1579220):

    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 
    } 
    

這是我做它的工作方式。希望能幫助到你!

相關問題