2012-07-17 68 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