SQL 'Execute As' Login Command and Linq to SQL

江枫思渺然 提交于 2019-12-01 10:27:55

I managed to get around this issue in my application by executing the query using ADO.NET classes.

SqlCommand cmd = new SqlCommand("EXECUTE AS USER = 'operator'");
cmd.Connection = dc.Connection as SqlConnection;
cmd.Connection.Open();
cmd.ExecuteNonQuery();

// do the rest of the queries using linq to sql

You may have already ruled this out, but one possible work around would be to simply create the data context with a different connection string.

To edit the connection string, you can set the DataContext.Connection.ConnectionString property. I've done it before in the partial method OnCreated(), which gets called when the data context gets created. I haven't tested but I think you could also do:

YourDataContext dc = new YourDataContext();
dc.Connection.ConnectionString = "connection string here";

Here's an article that describes this as well - http://www.mha.dk/post/Setting-DataContext-Connection-String-at-runtime.aspx

I was having a similar issue and by looking at ruskey's answer I was able to Execute as User but noticed that I was getting errors when running other queries after that. It was due to the missing Revert. So for anyone having a similar issue this is how the code looks like.

 SqlCommand cmd = new SqlCommand("EXECUTE AS USER = 'domain\\user';");
 OSSDBDataContext dc = new OSSDBDataContext();
 cmd.Connection = dc.Connection as SqlConnection;
 cmd.Connection.Open();
 cmd.ExecuteNonQuery();

 //Execute stored procedure code goes here

 SqlCommand cmd2 = new SqlCommand("REVERT;");
 cmd2.Connection = dc.Connection as SqlConnection;
 cmd2.ExecuteNonQuery();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!