ObjectContext をクエリする前に、毎回 SQL ストアド プロシージャを実行する必要があります。私が達成したいのは、CONTEXT_INFO
後でほとんどのクエリで使用される値に設定することです。
誰かがそれをしましたか?それは可能ですか?
[編集]
現在、接続を開き、次のように ObjectContext コンストラクターでストアド プロシージャを実行することで、これを実現しています。
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
}
}
次に、統合テストで:
[TestMethod]
public void TestMethod1()
{
using (var ctx = new MyEntitiesContext(1))
{
Assert.AreEqual(2, ctx.Roles.ToList().Count);
Assert.AreEqual(2, ctx.Users.ToList().Count);
}
}
ただし、これには接続を開いたままにしておく必要があります。常に CONTEXT_INFO が必要になるため、これはエラーが発生しやすく、別の開発者が簡単に実行できる可能性があります。
[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 のコードを使用し、すべてがうまくいかない - そして誰もどこで、なぜそれ以来すべてのテストは緑色です:/
[編集2]
このブログ投稿は確かに私の質問には答えませんが、実際に私の問題を解決します. 私の目的には、NHibernate を使用する方が適しているかもしれません :)