Is it possible to run native sql with entity framework?

For .NET Framework version 4 and above: use ObjectContext.ExecuteStoreCommand() if your query returns no results, and use ObjectContext.ExecuteStoreQuery if your query returns results.

For previous .NET Framework versions, here's a sample illustrating what to do. Replace ExecuteNonQuery() as needed if your query returns results.

static void ExecuteSql(ObjectContext c, string sql){
    var entityConnection =(System.Data.EntityClient.EntityConnection)c.Connection;
    DbConnection conn = entityConnection.StoreConnection;
    ConnectionState initialState = conn.State;
    try
    {if(initialState != ConnectionState.Open)
            conn.Open();//open connection ifnot already openusing(DbCommand cmd = conn.CreateCommand()){
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();}}
    finally
    {if(initialState != ConnectionState.Open)
            conn.Close();// only close connection ifnot initially open}}
posted @ 2013-06-18 16:49  赤狐(zcm123)  阅读(197)  评论(0编辑  收藏  举报