Executing an SQL stored procedure before each query created by EntityFramework

I need to execute a SQL stored procedure every time before I request my ObjectContext. What I want to achieve is to set the value CONTEXT_INFOto a value that will be used later in most of my queries.

Has anyone done this? Is it possible?

[EDIT]

I currently achieve this by opening a connection and executing a stored procedure in my ObjectContext constructor as follows:

public partial class MyEntitiesContext
{       
    public MyEntitiesContext(int contextInfo) : this()
    {
        if (Connection.State != ConnectionState.Open)
        {
            Connection.Open(); // open connection if not already open
        }

        var connection = ((EntityConnection)Connection).StoreConnection;

        using (var cmd = connection.CreateCommand())
        {
            // run stored procedure to set ContextInfo to contextInfo
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[dbo].[SetContextInfo]";
            cmd.Parameters.Add(new SqlParameter("@ci", _contextInfo));
            cmd.ExecuteNonQuery();
        }
        // leave the connection open to reuse later
    }
}

Then in my integration test:

[TestMethod]
public void TestMethod1()
{
    using (var ctx = new MyEntitiesContext(1))
    {               
        Assert.AreEqual(2, ctx.Roles.ToList().Count);
        Assert.AreEqual(2, ctx.Users.ToList().Count);
    }
}

But this requires me to leave the connection open - this is error prone, as I will always need CONTEXT_INFO, and another developer can easily do:

[TestMethod]
public void TestMethod2()
{
    using (var ctx = new MyEntitiesContext(1))
    {               
        // do something here
        // ... more here :)
        ctx.Connection.Close(); // then out of the blue comes Close();
        // do something here
        Assert.AreEqual(2, ctx.Roles.ToList().Count);
        Assert.AreEqual(2, ctx.Users.ToList().Count); // this fails since the where
        // clause will be:
        // WHERE ColumnX = CAST(CAST(CONTEXT_INFO() AS BINARY(4)) AS INT)
        // and CONTEXT_INFO is empty - there are no users with ColumnX set to 0
        // while there are 2 users with it set to 1 so this test should pass
    }
}

, , , - (YAY!), TestMethod2 - -, f'd up - , , :/

[EDIT2]

, , , . , NHibernate :)

+3
2
, . EFProvider wraper EFProviderWrappers. EFProviderWrapperConnection DbConnection.Open(). , . , .
0

.

, , , db.

+1

Source: https://habr.com/ru/post/1769483/


All Articles