开发者

MVC3 Multiple Conditions in where Clause

开发者 https://www.devze.com 2023-04-06 04:09 出处:网络
I have the following in my Controller 开发者_开发问答var workshop = registerDB.Workshops.Single(w => w.WorkshopID == id);

I have the following in my Controller

开发者_开发问答var workshop = registerDB.Workshops.Single(w => w.WorkshopID == id);
ViewBag.Enrollments = registerDB.Carts.Where(x => x.Username.Equals(User.Identity.Name));

and this in my view

@{ 
    //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>
    }

}
}

each time ViewBag.Enrollments = registerDB.Carts.Where(x => x.Username.Equals(User.Identity.Name)); returns no results, I get an error saying System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first. and this line is highlighted

if (timeSlot == item.Workshop.TimeSlot)


Try calling .ToList() in the controller to eagerly fetch the results:

ViewBag.Enrollments = registerDB
    .Carts
    .Where(x => x.Username.Equals(User.Identity.Name))
    .ToList();


You are checking that item != null but not that item.Workshop != null before trying to use it. It would appear that is perhaps the error, but why it's raising InvalidOperationException rather than NullReferenceException I don't know.

Try:

if (item != null && item.Workshop != null)
{
    if (timeSlot == item.Workshop.TimeSlot)
    {
        <h3>@timeSlot</h3>
    }
}


Could you put the single call in your model:

workshops workshop = registerDB.Workshops.Single(w => w.WorkshopID == id);

And then in your controller set the ViewBag:

try
{
ViewBag.Enrollments = workshop.Carts.Where(x => x.Username.Equals(User.Identity.Name));
}
catch
{
ViewBag.Enrollments = "There are no results";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消