如何修复'System.InvalidOperationException'连接问题

时间:2019-07-04 02:05:40

标签: asp.net-mvc database invalidoperationexception

我的应用程序始终在加载时遇到System.InvalidOperationException错误。 我将dbContext用于控制器中的每个方法。 我需要做些什么来消除错误?

我已将dbContext的访问权限从静态更改为私有。 我确实处理过dbContext。

没有using语句,有没有办法正确地完成它?

dbContext的初始化和声明

public class AdjustmentController : BaseController
{
    private DBEntities db = new DBEntities();
}

处置dbContext

protected override void Dispose(bool disposing)
{
    if (disposing)
        db.Dispose();

    base.Dispose(disposing);
}

调用dbContext

public ActionResult Details(string ID)
{
    var data = db.GetAdjustmentByID(ID);

    var model = new AdjustmentViewModel()
    {
        ID = data.ID,
    }

    return View(model);
}

异常消息

System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is open.
   at System.Data.SqlClient.SqlConnection.GetOpenConnection(String method)
   at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
   at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

我希望不使用using语句即可解决此问题。

0 个答案:

没有答案