Entity Framework ObjectContext -> raw SQL calls to native DBMS

二次信任 提交于 2019-12-19 08:55:06

问题


I have an app using the ADO.NET entity framework (the VS2008 version, not the newer, cooler one) and I need to be able to make a call down to the underlying DBMS (it's postgres) in order to call some SQL that Entity Framework doesn't support.

Is there a way to go from an Entity Framework ObjectContext to something that will let me execute raw SQL? (I need to run a TRUNCATE TABLE before inserting) I'm OK with a hacky solution (e.g. pull out the DBMS's connection string info from EF, and use that to create a connection using the postgres ADO.NET provider) but don't want to manage two sets of connection strings (one for entity framework, one for ADO.NET).

I'm aware of the limitatons of Entity Framework's first version, but it's not worth the investment required to switch this app to another ORM, and using EF 4.0 isn't an option either.

Any ideas?

BTW, this is the same question as Is it possible to run native sql with entity framework?, but the workaround described in that answer won't work for me since I really do need to execute raw SQL.


回答1:


Craig's answer, while it didn't work as-is, got me looking in the right direction. Turns out there's an EntityConnection.StoreConnection property which gets you a connection to the underlying DBMS. So executing "native" SQL is as easy as this:

    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
        }
    }



回答2:


Yes, you can do this. Look at EntityConnection.StoreConnection. You can get the connection out of the ObjectContext.




回答3:


According to this post there is no support of DML in Entity Framework V1.

But there is support of stored procedures, but only such of them that return entities. That means if you create stored procedure in that way (sql server syntax):

CREATE PROCEDURE [dbo].[usp_trncate]
AS
BEGIN
 truncate table t1
END

You can't import it as function (actually you can, but it won't work - no code for this function will be generated)

I have found crutch solution to achive the goal: if you define sp as below:

CREATE PROCEDURE [dbo].[usp_trncate]
AS
BEGIN
 truncate table t1

 select top 1 * from t1
END

you can import as function and use it in your code like this:

TestEntities context = new TestEntities();
context.TruncateTable();

(TruncateTable is the name of imported function)

I think there is another (better) solution. Other ways to digg are to tinker with .edmx file to make sp without return works or write another sp and map it to table insert function (that sp must truncate table and insert row)

I hope it will help you.




回答4:


Thanks Justin. I spent hours trying to figure out why the StoreConnection property was not available on my Entity Framework connection....

The key piece for me was the fact that you have to formally cast your EF connection as a System.Data.EntityClient.EntityConnection:

var newConn = (System.Data.EntityClient.EntityConnection)db.Connection;

Once I did that it everything else made sense.



来源:https://stackoverflow.com/questions/1576067/entity-framework-objectcontext-raw-sql-calls-to-native-dbms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!