在应用程序运行期间发生DropDownList错误
在应用程序运行期间发生DropDownList错误
我在DropDownList上遇到了问题。当我通过免费的主机运行应用程序时,我遇到了以下错误信息:
错误:已经有一个与此命令相关联的打开的DataReader,必须先关闭它。
错误来源信息如下:
第51行:@Html.DropDownList("ScreeningId", null, htmlAttributes: new { @class = "form-control" })
我额外添加了“View”和“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
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)
{
// 检查座位是否已经被预订
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);
}
}
部分View文件内容如下:
@Html.LabelFor(model => model.Screening, "Seans", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownList("ScreeningId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Screening, "", new { @class = "text-danger" })
[InvalidOperationException: 已经有一个与此命令相关联的打开的DataReader,必须先关闭它。]
堆栈跟踪:
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.
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: 在执行命令定义时发生错误。有关详细信息,请参阅内部异常。]
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.
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.<>c__DisplayClass7.
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.
System.Data.Entity.DynamicProxies.Screening_333144174B6E44255ACF2CFB15F4499A880DB4ECDBA71E01178031C116125BB8.get_Film() +23
CinemaTicketReservation.Models.Screening.get_Description() +34
[TargetInvocationException: 对象“System.Data.Entity.DynamicProxies.Screening_333144174B6E44255ACF2CFB15F4499A880DB4ECDBA71E01178031C116125BB8”的属性访问器“Description”引发了以下异常:“在执行命令定义时发生错误。有关详细信息,请参阅内部异常。”]
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.
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.
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.
System.Web.Mvc.Async.<>c__DisplayClass46.
System.Web.Mvc.Async.<>c__DisplayClass33.
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.
System.Web.Mvc.Async.<>c__DisplayClass21.
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.
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.
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
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.
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]
问题的原因是在控制器中调用了AppDbContext,这是错误的,并且会导致许多错误。在ReservationsController中声明并实例化了dbcontext,但在使用后没有处理掉上下文。
解决方法是使用一个ApplicationService类,并在控制器中注入接口。在ApplicationService类中使用using(AppDbContext db){return db.Reservations();},这样上下文就会被处理掉。
是的,我上面的代码中没有放置dispose,但是我可以说我在代码结束时使用了它。这个控制器有很长的代码,所以我只放置了受影响的部分。我现在在控制器中添加了处理代码。