2011-09-21 111 views
0

我有我的控制器MVC3在where子句

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

嘗試調用.ToList()在控制器中預先抓取結果:

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

我如何檢查ViewBag.Enrollments在用戶沒有做出任何選擇的情況下? –

0

您檢查item != null但不是item.Workshop != null嘗試使用它之前。這似乎也許是錯誤,但爲什麼它提高InvalidOperationException,而不是NullReferenceException我不知道。

嘗試:

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

我試過了,但仍然有相同的錯誤 –

+0

@EdgarOchieng' - 不確定。 – ChrisF

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