gpt4 book ai didi

nhibernate - 在EntityFramework生成的每个查询之前执行一个SQL存储过程

转载 作者:行者123 更新时间:2023-12-03 13:12:39 25 4
gpt4 key购买 nike

在查询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
}
}


上面的意思是我可以像在测试中那样编写代码,并且一切都是绿色的(是!),但是随后我的同事在他的业务逻辑中的某个地方使用了TestMethod2中的代码,这一切都搞砸了-而且没人知道在哪里,为什么自从所有测试均为绿色:/

[EDIT2]

This blog post当然不能回答我的问题,但实际上可以解决我的问题。也许与NHibernate一起使用会更适合我的目的:)

最佳答案

我们已经使用了这种模式。

但是我们的方法是将存储过程称为每个数据库上下文中的第一个操作。

关于nhibernate - 在EntityFramework生成的每个查询之前执行一个SQL存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3930517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com