In entity framework, can I run SQL?

entity-framework

Question

Is it possible to directly execute a SQL transaction using Entity Framework produced calls? Or do I need to write a method first, then use the entity framework to call it?

1
5
11/5/2009 10:56:34 PM

Accepted Answer

I recently searched for this myself and came across this example; perhaps it will be helpful.

  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();  
            using (DbCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
            }
        }
        finally
        {
            if (initialState != ConnectionState.Open)
                conn.Close(); 
        }
    }
10
11/6/2009 3:47:18 PM

Popular Answer

This is really simple with EF 4.0 since there are new methods on theObjectContext that enable direct execution of store operations (such as SQL)

Check this out: ExecuteStoreCommand

If you really want to, you may still run a query on the database if you are still running EF 3.5 SP1 as follows:

var econn = ctx.Connection as EntityConnection;
var dbconn = econn.StoreConnection;

You now have access to a connection (dbconn) to the underlying database and may run queries and other ADO.NET code as usual.

Hope this is useful.

Alex



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow