我的控制器中有以下内容
var workshop = registerDB.Workshops.Single(w => w.WorkshopID == id);
ViewBag.Enrollments = registerDB.Carts.Where(x => x.Username.Equals(User.Identity.Name));
这在我看来
@{
//var carts = Model.Carts.Where(x => x.Username.Equals(User.Identity.Name));
var carts = ViewBag.Enrollments;
var timeSlot = Model.TimeSlot;
}
@{
foreach (var item in carts)
{
if (item != null)
{
if (timeSlot == item.Workshop.TimeSlot)
{
<h3>@timeSlot</h3>
}
}
else
{
<h3>Does not Exist</h3>
}
}
}
每次ViewBag.Enrollments = registerDB.Carts.Where(x => x.Username.Equals(User.Identity.Name));
都没有返回任何结果时,我收到错误提示System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
并且此行突出显示
if (timeSlot == item.Workshop.TimeSlot)
答案 0 :(得分:0)
尝试在控制器中调用.ToList()
以急切地获取结果:
ViewBag.Enrollments = registerDB
.Carts
.Where(x => x.Username.Equals(User.Identity.Name))
.ToList();
答案 1 :(得分:0)
在尝试使用之前,您正在检查item != null
但不是item.Workshop != null
。看起来这可能是错误,但为什么它会提升InvalidOperationException
而不是NullReferenceException
我不知道。
尝试:
if (item != null && item.Workshop != null)
{
if (timeSlot == item.Workshop.TimeSlot)
{
<h3>@timeSlot</h3>
}
}
答案 2 :(得分:0)
你能把单一电话放在你的模型中吗?
workshops workshop = registerDB.Workshops.Single(w => w.WorkshopID == id);
然后在你的控制器中设置ViewBag:
try
{
ViewBag.Enrollments = workshop.Carts.Where(x => x.Username.Equals(User.Identity.Name));
}
catch
{
ViewBag.Enrollments = "There are no results";
}