【发布时间】:2017-06-13 19:43:43
【问题描述】:
我有一个使用 EF6 的应用程序。我需要执行存储过程,所以我执行以下操作:
using (SqlConnection conn = new SqlConnection(context.Database.Connection.ConnectionString))
{
SqlCommand cmd = new SqlCommand("dbo.ExampleStoredProcedure", conn)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.Add(new SqlParameter("@param1", "parameterValue"));
SqlDataAdapter da = new SqlDataAdapter { SelectCommand = cmd };
durations = new DataSet();
da.Fill(durations);
}
我来自 Web.config 的连接字符串是:
<add name="MyEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="data source=MyServer\DEV;initial catalog=MyApp;User Id=UserId;Password=password123;Application Name=Connection Secured;integrated security=false;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
当上面的代码运行时出现异常:
Login failed for user 'UserId'.
该异常还包含 SQL 错误代码:18456。 通过使用此 SQL 帐户登录 SQL Server 并运行相关存储过程,我确认用户拥有对此 SQL Server、数据库、实例和存储过程的完全访问权限。
我也尝试定义一个新的 SqlConnection 对象:
SqlConnection newCon = new SqlConnection("Server=MyServer\\DEV;Database=MyApp;User Id=UserId;Password = password123;");
并针对它执行存储过程——这次它成功了。所以我确实有一个解决方法,但想使用 context.Database.Connection.ConnectionString 对象来避免 web.config 文件中有多个连接字符串。
有什么建议吗?
【问题讨论】:
-
检查
context.Database.Connection.ConnectionString的值。 -
您的 UserID 用户是否具有在数据库上执行存储过程的适当权限?
-
@Chad 是的,来自我的问题文本:“我通过使用此 SQL 帐户登录 SQL Server 并运行存储过程,确认用户对此 SQL Server、数据库、实例和存储过程具有完全访问权限有问题。”
-
@Kyle 这里是:数据源=MyServer\DEV;初始目录=MyApp;用户ID=用户ID;应用程序名称=连接安全;集成安全=false;MultipleActiveResultSets=True;App=EntityFramework
-
你有没有试过让实体连接和第二个一样,看看是否有效?
标签: c# sql-server entity-framework stored-procedures