2012-07-17 71 views
0

我一直在尋找這個問題了大約兩個星期,現在並認爲這是一次我尋求幫助......MVC音樂商店鏈接表數據

我試圖讓MVCMusicStore購物車教程工作第8部分:http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-8。我的項目的主要區別在於,我使用的是數據庫優先(而不是Code First,用於MVC實踐/託管數據庫)。

類代碼:

public partial class Cart 
{ 
    public int RecordId { get; set; } 
    public string CartId { get; set; } 

    public int AlbumId { get; set; } 

    public Nullable<int> Count { get; set; } 
    public Nullable<System.DateTime> DateCreated { get; set; } 

    public virtual Album Album { get; set; } 
} 

public partial class Album 
{ 
    public int AlbumId { get; set; } 
    public Nullable<int> GenreId { get; set; } 
    public Nullable<int> ArtistId { get; set; } 
    public string Title { get; set; } 
    public Nullable<decimal> Price { get; set; } 
    public string AlbumArtUrl { get; set; } 

    public virtual Genre Genre { get; set; } 
    public virtual Artist Artist { get; set; } 
} 

public class ShoppingCartViewModel 
{ 
    public List<Cart> CartItems { get; set; } 
    public decimal CartTotal { get; set; } 
} 

函數來填充CartItems在ShoppingCartViewModel:

public List<Cart> GetCartItems() 
{ 
    return db.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList(); 
} 

.cshtml頁:

@model BoothPimps.ViewModels.ShoppingCartViewModel 

@foreach (var item in Model.CartItems) 
{ 
    <tr id="[email protected]"> 
     <td> 
      @Html.ActionLink(item.Album.Title, "Details", "Store", new { id = item.AlbumId }, null) 
     </td> 
    </tr> 
} 

這裏是Model.CartItems的圖像,填充除連結相簿資料外的所有內容: http://s1253.photobucket.com/albums/hh585/codingcoding1/?action=view&current=image1.jpg (項目名稱去掉無論scribbed)

代碼中的錯誤的位置:

@Html.ActionLink(item.Album.Title, "Details", "Store", new { id = item.AlbumId }, null) 

問題:item.Album總是空。

Album.AlbumId = Cart.AlbumId應該將相冊數據鏈接到購物車,以便它不會返回null,但它不起作用。在前面的教程但是當我做同樣的事情,但是從專輯獲得流派或藝術家的數據鏈接的數據工程,我能夠檢索值,就像這樣:

@Html.DisplayFor(model => model.Genre.Name) 
@Html.DisplayFor(model => model.Artist.Name) 

那麼怎麼來model.Genre藝術家返回值,但item.Album爲空?我是不是使用「虛擬」關鍵字以相同的方式鏈接這些值?我錯過了什麼?

感謝您看看這個。

回答

0

想通了。

myProject.Context.cs(從.edmx文件生成)在Web.Config文件中生成了新的connectionString信息,我不得不在我的代碼中引用它。我的不正確代碼實際上是在使用實體對象的舊版本,並且應該一直指向新的。

private Entities = new Entities(); 
// private MyProjectDb = new MyProjectDb(); 

混淆起來,因爲MVC音樂商店教程使用代碼第一次和僞造數據,所以我不知道我不得不改變這段代碼,直到後來上。

0

您是否有可能在購物車中確實有空物品,因爲它的相冊?
嘗試在此操作結束時放置一個斷點,並檢查模型的組成部分。

使用調試器找到沒有更多item.Album的點,並且確保檢查數據庫中沒有Album的任何項目。 一旦你知道錯誤來自哪裏,你很可能會修復它,但如果沒有,在這裏發佈你的發現。

+0

爲您截圖並將其添加到帖子中。您也可以使用此鏈接:http://s1253.photobucket.com/albums/hh585/codingcoding1/?action=view¤t=image1.jpg – ForeverLearningAndCoding 2012-07-18 02:09:19