2009-11-10 98 views
3

我移植的LINQ到SQL來實體框架運行的應用程序,並且我無法找到一個相當於ExecuteCommand實體框架中的LINQ-to-SQL的ExecuteCommand等價於什麼?

db.ExecuteCommand("INSERT Infos (Title) VALUES ('this is an added title')"); 

我發現this site告訴我,有可能實施ExecuteCommand爲您的ObjectContext的擴展方法,保留現有代碼不變,通過在項目中添加此代碼到一個靜態方法:

public static int ExecuteCommand(this ObjectContext objectContext, 
           string command) { 
    DbConnection connection = ((EntityConnection)objectContext.Connection).StoreConnection; 
    bool opening = (connection.State == ConnectionState.Closed); 
    if (opening) 
     connection.Open(); 

    DbCommand cmd = connection.CreateCommand(); 
    cmd.CommandText = command; 
    cmd.CommandType = CommandType.StoredProcedure; 
    try { 
     return cmd.ExecuteNonQuery(); 
    } 
    finally { 
     if (opening && connection.State == ConnectionState.Open) 
      connection.Close(); 
    } 
} 

但我試過把它放在我使用它的類中,(2)在實體生成的類文件中,(3)在項目中的靜態類中,但總是得到各種錯誤。 我需要把這個方法準確的放在哪裏?

上述網站說:

ExecuteCommand被視爲 在將來的 版本增強實體框架

不ExecuteCommand()存在於最新版本的實體框架?我正在使用隨Visual Studio 2008 SP1一起安裝的實體框架。

+0

嘗試使用擴展方法時,您會得到什麼錯誤? – Konamiman 2009-11-10 15:19:25

+0

好吧,它編譯時,我指定我把它作爲*靜態*,所以它似乎工作,但我無法運行應用程序來測試它,因爲在這個問題中描述的另一個問題:http: //stackoverflow.com/questions/1708964/why-do-i-get-this-error-when-i-try-to-open-an-mdf-database-via-path-filename-in-e – 2009-11-10 15:50:31

+0

這: 'CommandType.StoredProcedure'也可能有影響,因爲我猜你想要執行一個請求,而不是存儲過程。 – 2010-04-27 12:49:01

回答

2

.NET Framework 4的ObjectContext類有ExecuteStoreCommandExecuteStoreQuery方法,這似乎是你在找什麼。

+0

另請參閱http://blogs.msdn.com/alexj/archive/2009/11/07/tip-41-how-to-execute-t-sql-directly-against-the-database.aspx(對於EF 1)。 – 2009-11-10 15:22:00