我正在使用带有 Entity Framework 5 和 SQL Server 2008 的 Visual Studio 2012 编写数据库应用程序。我希望 Entity Framework 模拟 SQL Server 用户(即没有登录的用户)。我为数据库上下文创建了一个新的构造函数,MyDatabaseEntities
其中包括一个用于模拟用户名称的参数。这是我编写的代码:
public partial class MyDatabaseEntities
{
private String _impersonateUser = null;
public MyDatabaseEntities(String impersonateUser)
: base("MyConnectionString")
{
_impersonateUser = impersonateUser;
this.Database.Connection.StateChange += Connection_StateChange;
}
void Connection_StateChange(object sender, StateChangeEventArgs e)
{
if (e.CurrentState == ConnectionState.Open && e.OriginalState != ConnectionState.Open)
{
using (var cmd = this.Database.Connection.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("user", _impersonateUser));
cmd.CommandText = "EXECUTE AS USER = @user";
cmd.ExecuteNonQuery();
}
}
}
我不得不添加支票...
if (e.CurrentState == ConnectionState.Open && e.OriginalState != ConnectionState.Open)
...因为Connection_StateChange
即使状态没有改变,方法 method 似乎也会执行。那么问题是当我运行代码两次时,
public void RunSimpleQuery()
{
using (MyDatabaseEntities context = new MyDatabaseEntities("UserName"))
{
var result = context.TableName.ToList();
}
}
...实体框架抛出一个SqlException
:
当前命令发生严重错误。结果(如果有)应被丢弃。\r\n当前命令出现严重错误。结果,如果有的话,应该丢弃。
有任何想法吗?
更新 1
我在上面的代码中,我改变了......
cmd.CommandText = "EXECUTE AS USER = @user;";
...到...
cmd.CommandText = "REVERT; EXECUTE AS USER = @user;";
...我仍然得到同样的SqlException
错误。