I’ve been looking at this problem for about two weeks now and think it’s time I ask for help…
I’m trying to get the MVCMusicStore shopping cart tutorial working in Part 8: http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-8. The main difference in my project is that I am using Database First (rather than Code First, for MVC practice with live/hosted databases).
Class code:
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; }
}
Function to populate CartItems in ShoppingCartViewModel:
public List<Cart> GetCartItems()
{
return db.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();
}
.cshtml page:
@model BoothPimps.ViewModels.ShoppingCartViewModel
@foreach (var item in Model.CartItems)
{
<tr id="row-@item.RecordId">
<td>
@Html.ActionLink(item.Album.Title, "Details", "Store", new { id = item.AlbumId }, null)
</td>
</tr>
}
Here is an image of Model.CartItems, populated with everything EXCEPT the linked Album data:
http://s1253.photobucket.com/albums/hh585/codingcoding1/?action=view¤t=image1.jpg
(Project name removed wherever scribbed)
CODE ERRORS HERE:
@Html.ActionLink(item.Album.Title, "Details", "Store", new { id = item.AlbumId }, null)
Problem: item.Album is always null.
Album.AlbumId = Cart.AlbumId should be linking the Album data to the Cart so that it doesn’t return null but it doesn’t work. In previous tutorials however when I do the same thing but to get Genre or Artist data from the Album the linked data works and I’m able to retrieve the values, like so:
@Html.DisplayFor(model => model.Genre.Name)
@Html.DisplayFor(model => model.Artist.Name)
So how come model.Genre and model.Artist return values but item.Album is null? Aren’t I linking these values the same way using the “virtual” keyword? What am I missing?
Thanks for taking a look at this.
Figured it out.
myProject.Context.cs (generated from the .edmx file) generated new connectionString info in the Web.Config file and I had to refer to that in my code. My incorrect code was really using an older version of an Entities object and should’ve been pointing to the new one.
The confusion arose because the MVC Music Store tutorial uses Code First and fake data, so I didn’t realize I had to change this piece of code until later on.