SQL 'Execute As' Login Command and Linq to SQL

我的梦境 提交于 2019-12-01 09:50:16

问题


I am trying to execute a sql query as another login using the 'Execute As' command. I am using Linq to SQL, so I've generated a Data Context class and I am using the ExecuteQuery method to run the 'Execute As' SQL command. I then call a Linq to SQL command that is successful. However, every subsequent query fails with the following error:

A severe error occurred on the current command. The results, if any, should be discarded.

Here is the code snippet that I have tried:

SummaryDataContext summary = new SummaryDataContext();
summary.ExecuteQuery<CustomPostResult>(@"Execute as Login='Titan\Administrator'");
var test = summary.Customers.First();
var test2 = summary.Products.ToList();

No matter what query I run on the second query I receive the error message from above. Any help would be appreciated.


回答1:


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



回答2:


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




回答3:


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();


来源:https://stackoverflow.com/questions/1902084/sql-execute-as-login-command-and-linq-to-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!