是否可以使用实体框架运行本机 sql? [英] Is it possible to run native sql with entity framework?

查看:31
本文介绍了是否可以使用实体框架运行本机 sql?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试搜索表中的 XML 字段,EF 不支持此操作.

I am trying to search an XML field within a table, This is not supported with EF.

不使用纯 Ado.net 是否可以通过 EF 获得本机 SQL 支持?

Without using pure Ado.net is possible to have native SQL support with EF?

推荐答案

对于 .NET Framework 版本 4 及更高版本:使用 ObjectContext.ExecuteStoreCommand() 如果您的查询没有返回结果,并使用 ObjectContext.ExecuteStoreQuery 如果您的查询返回结果.

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.

对于以前的 .NET Framework 版本,这里有一个示例来说明要执行的操作.如果您的查询返回结果,则根据需要替换 ExecuteNonQuery().

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆