【问题标题】:Unable to execute stored procedure in Entity Framework 6无法在实体框架 6 中执行存储过程
【发布时间】: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=&quot;data source=MyServer\DEV;initial catalog=MyApp;User Id=UserId;Password=password123;Application Name=Connection Secured;integrated security=false;MultipleActiveResultSets=True;App=EntityFramework&quot;" 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


【解决方案1】:

此行为是出于安全原因而设计的,因为this 回答了建议的问题。我添加了 Persist Security Info=True 到 Entity Framework 在 web.config 文件中生成的连接字符串,我能够重用 context.Database.Connection.ConnectionString 来使用 ADO 执行存储过程。

【讨论】:

    【解决方案2】:

    您不需要(也不应该)为此打开单独的连接。您可以使用 DbContext 使用的相同连接。

    只需打开连接(在释放 DbContext 时它将关闭)并将其强制转换为 SqlConnection。例如

            db.Database.Connection.Open();
            var con = (SqlConnection)db.Database.Connection;
    

    【讨论】:

      猜你喜欢
      • 2013-12-25
      • 1970-01-01
      • 2016-10-03
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 2015-06-05
      • 1970-01-01
      相关资源
      最近更新 更多