是否可以使用实体框架运行本机sql? [英] Is it possible to run native sql with entity framework?
问题描述
不使用纯粹的Ado.net可以拥有本机SQL支持与EF?
对于.NET Framework版本4及以上版本:使用 ObjectContext.ExecuteStoreCommand()
if您的查询不会返回结果,并使用 ObjectContext.ExecuteStoreQuery
如果您的查询返回结果。
对于以前的.NET Framework版本,以下是一个示例说明要做什么。如果查询返回结果,则根据需要替换ExecuteNonQuery()。
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(); //打开连接如果尚未打开
使用(DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
finally
{
if(initialState!= ConnectionState.Open)
conn.Close(); //仅关闭连接,如果不是最初打开
}
}
I am trying to search an XML field within a table, This is not supported with EF.
Without using pure Ado.net is possible to have native SQL support with EF?
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 if not already open
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close(); // only close connection if not initially open
}
}
这篇关于是否可以使用实体框架运行本机sql?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!