0

I have problem with DropDownList. When I run application via free hosting I have

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

With information about source of error:

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

I add additionally files View and Controller:

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

Part of View file

<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.]

Stack Trace

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

I saw in some topics, that MARS (MultipleActiveResultSets=true) is needed here. I already add it, and still it's not working. Do you have some ideas? This topic have reference to: dropdownlist looks OK but not working [duplicate]

Frihu
  • 43
  • 9

1 Answers1

0

I can see architectural problems in your code.

You are calling the AppDbContext on the controller which is wrong and will result in a lot of errors. you have declared and instationated dbcontext on the ReservationsController but you are not disposing off the context after use.

Instead use an ApplicationService Class, and inject the interface on the controller. as such you can go to the ApplicationService class and use: using (AppDbContext db){return db.Reservations();} as such the context is disposed off.

Jack M
  • 2,564
  • 4
  • 28
  • 49
  • Yes, I did not put dispose in code above, but I can say that I use it at the end of code.. This controller have long code so I put only affected part. I add disposing in Controller right now. – Frihu Jan 18 '18 at 08:59