应用程序运行期间DropDownList错误

时间:2018-01-18 08:13:36

标签: c# asp.net

我有DropDownList的问题。当我通过免费托管运行应用程序时,我有

  

错误:已经有一个与之关联的开放DataReader   必须先关闭的命令。

有关错误来源的信息:

Line 51:             @Html.DropDownList("ScreeningId", null, htmlAttributes: new { @class = "form-control" })

我添加了另外的文件查看控制器

    public class ReservationsController : Controller
    {
        private AppDbContext db = new AppDbContext();

        // GET: Reservations
        public ActionResult Index()
        {
            return View(db.Reservations.ToList());
        }

        // GET: Reservations/Create
        public ActionResult Create()
        {
            ViewBag.ScreeningId = new SelectList(db.Screenings, "Id", "Description");

            HashSet<int> seats = new HashSet<int>(db.Reservations.Select(x => x.SeatNumber));
            ViewBag.Seats = seats;
            return View();
        }

        // POST: Reservations/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FirstName,SecondName,Phone,SeatNumber,ScreeningId")] Reservation reservation)
        {
            ViewBag.ScreeningId = new SelectList(db.Screenings, "Id", "Description");
            if (ModelState.IsValid)
                {

                // sprawdzamy czy miejsce bylo juz zajete
                if (db.Reservations.Select(x => x.SeatNumber).Contains(reservation.SeatNumber))
                {

                    return View(reservation);
                }
                else
                {
                    db.Reservations.Add(reservation);
                    db.SaveChanges();
                }
                if (Session["Login"] != null)
                {
                    return RedirectToAction("Index");
                }
                return RedirectToAction("Success");
            }

            return View(reservation);
        }
protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

查看文件的一部分

<div class="form-group">
    @Html.LabelFor(model => model.Screening, "Seans", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("ScreeningId", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Screening, "", new { @class = "text-danger" })
    </div>
</div>

[InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]

堆栈跟踪

System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +1545589
       System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +89
       System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +268
       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) +118
       System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
       System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +161
       System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
       System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
       System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c) +9
       System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
       System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +356
       System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
       System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
       System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +37

    [EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
       System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +112
       System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +744
       System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__6() +97
       System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
       System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__5() +154
       System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +189
       System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +279
       System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption) +31
       System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption) +139
       System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad() +333
       System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty(TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject) +87
       System.Data.Entity.Core.Objects.Internal.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item) +106
       System.Data.Entity.DynamicProxies.Screening_333144174B6E44255ACF2CFB15F4499A880DB4ECDBA71E01178031C116125BB8.get_Film() +23
       CinemaTicketReservation.Models.Screening.get_Description() +34

    [TargetInvocationException: Property accessor 'Description' on object 'System.Data.Entity.DynamicProxies.Screening_333144174B6E44255ACF2CFB15F4499A880DB4ECDBA71E01178031C116125BB8' threw the following exception:'An error occurred while executing the command definition. See the inner exception for details.']
       System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component) +378
       System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName) +87
       System.Web.UI.DataBinder.Eval(Object container, String[] expressionParts) +86
       System.Web.UI.DataBinder.Eval(Object container, String expression) +95
       System.Web.Mvc.MultiSelectList.Eval(Object container, String expression) +35
       System.Web.Mvc.<>c__DisplayClass2.<GetListItemsWithValueField>b__1(Object item) +86
       System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +164
       System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +387
       System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
       System.Web.Mvc.MultiSelectList.GetListItemsWithValueField() +145
       System.Web.Mvc.MultiSelectList.GetListItems() +44
       System.Web.Mvc.MultiSelectList.GetEnumerator() +8
       System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +375
       System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
       CinemaTicketReservation.Controllers.ReservationsController.Create() +248
       lambda_method(Closure , ControllerBase , Object[] ) +62
       System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
       System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
       System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
       System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
       System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
       System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
       System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +228
       System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
       System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
       System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
       System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
       System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
       System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
       System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
       System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9987157
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

我在一些主题中看到,这里需要MARS(MultipleActiveResultSets=true)。我已经添加了它,但仍然无法正常工作。你有什么想法吗? 本主题参考: dropdownlist looks OK but not working [duplicate]

1 个答案:

答案 0 :(得分:0)

我可以在代码中看到架构问题。

您在控制器上调用AppDbContext是错误的并且会导致很多错误。你已经在ReservationsController上声明并设置了dbcontext,但是你在使用后没有处理掉上下文。

而是使用ApplicationService类,并在控制器上注入接口。因此,您可以转到ApplicationService类并使用:using(AppDbContext db){return db.Reservations();}这样处理上下文。