2012-04-13 98 views
1

我正在使用一個類來存儲數據,然後使用控制器和視圖來顯示網站上的屏幕上的數據使用MVC3但是我遇到了一個錯誤,幫助將不勝感激。序列不包含任何元素

類別:

public class SampleData : DropCreateDatabaseIfModelChanges<TicketBookingEntities> 
    { 
     protected override void Seed(TicketBookingEntities context) 
     { 
      var productions = new List<Production> 
      { 
       new Production { Name = "Peter Pan" }, 
       new Production { Name = "Mary Poppins" }, 
       new Production { Name = "Pirates of the Carribean" }, 
       new Production { Name = "Joseph" }, 
       new Production { Name = "Billy Elliot" }, 

      }; 

      var directors = new List<Director> 
      { 
       new Director { Name = "Jason Brown" }, 
       new Director { Name = "Dan Elish" }, 
       new Director { Name = "Lee Hall" }, 
       new Director { Name = "Billie Armstrong" }, 
       new Director { Name = "Willy Russell" }, 

      }; 

      new List<Performance> 
      { 


       new Performance {Title = "Test", Genre = productions.Single(g => g.Name == "Peter Pan"), Director = directors.Single(a => a.Name == "Jason Brown"), Price = 9.99M, AlbumArtUrl = "/Content/Images/placeholder.gif" }, 


      }.ForEach(a => context.Performances.Add(a)); 
     } 
    } 
} 

控制器:

public ActionResult Browse(string genre) 
     { 
      var productionModel = storeDB.Productions.Include("Performances") 
       .Single(g => g.Name == genre); 

      return View(productionModel); 

     } 

檢視:

@model Assignment2.Models.Production 

@{ 
    ViewBag.Title = "Browse"; 
} 

<h2>Browsing Production: @Model.Name</h2> 
<ul> 
    @foreach (var performance in Model.Performances) 
    { 
     <li> 
      @performance.Title 

     </li> 
    } 

</ul> 

的錯誤:

Sequence contains no elements 
+0

你是什麼模型? – MikeSW 2012-04-13 18:51:10

+0

在你的'foreach'之前加上'@if(Model.Performances)'來檢查這個集合是否是'null' – MilkyWayJoe 2012-04-13 18:51:14

回答

1

您沒有列表,只有一個元素。取出foreach循環。

+0

我原本有一個列表,但是我列出了一些列表,因爲發生了錯誤而只剩下了測試它的一個項目 – user1300580 2012-04-13 18:49:47

+0

@ user1300580 - 嘗試製作更詳細的視圖模型,實體模型不能很好地用作視圖模型。 – 2012-04-13 18:50:33

+0

我該怎麼做? – user1300580 2012-04-13 18:53:47

0

管理解決問題,改變控制器上的流派到生產

相關問題