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}}
上一篇:div 加滚动条


下一篇:CSS3实战开发: 折角效果实战开发