【发布时间】:2015-11-20 20:59:00
【问题描述】:
通过 MVC MusicStore 学习 MVC 时让我头疼。 Model.Artist.Name for Details View page 出现此错误。
我的 Storecontroller Details 方法应该没问题。
public ActionResult Details(int id)
{
//returns and albums searched from the id
var albums = storeDB.Albums.Find(id);
return View(albums);
}
这就是我输出视图的方式
<li>Price : <%=Model.Price %></li>
<li>Artist : <%=Model.Artist.Name%></li>
价格合理,它只显示 Model.Genre.Name 和 Artist.Name 错误。我怀疑 sampledata.cs 中这些属性的声明导致了这个问题
Artist = artists.Single(a => a.Name == "Aaron Copland & London Symphony Orchestra")
但我对此的了解太薄弱,无法弥补。请帮忙 。
好吧,这个值是从一个类似这样的类文件中获取的
protected override void Seed(MusicStoreEntities context)
{
var artists = new List<Artist>
{
new Artist { Name = "Aaron Copland & London Symphony Orchestra" },
etcetc
}
new List<Album>
{
new Album { Title = "ABC", Artist= artists.Single(g => g.Name == "Test")}
}
}
注意值是如何分配的,我可以很好地访问 Model.Title(其中 Model 是简写),但是 Model.Artist.Name 导致了我这个错误。
已解决
好的,通过在 Album 类的 Artist 和 Genre 声明中添加 virtual keyword 使其工作。但我仍然不确定会发生什么,并希望有人关心一下。
在我的相册类中,在解决之前它看起来像这样
public class Album
{
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public string AlbumArtUrl { get; set; }
public Genre Genre { get; set; }
public Artist Artist { get; set; }
}
通过添加Virtual关键字解决了由Genre和Artist引起的错误
public virtual Artist Artist { get; set; }
不知何故,我仍然无法证明发生了什么,并希望了解更多信息。有人愿意解释吗?
它是这样的,Album.cs
namespace MvcMusicStore.Models
{
public class Album
{
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
}
使用 EF MusicStore.cs
namespace MvcMusicStore.Models
{
//represent entity framework , handle create ,read , update and del ops
public class MusicStoreEntities : DbContext
{
public DbSet<Album> Albums { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Artist> Artists { get; set; }
}
}
并在 StoreController.cs 中实现
MusicStoreEntities storeDB = new MusicStoreEntities();
public ActionResult Details(int id)
{
//returns and albums searched from the id
var albums = storeDB.Albums.Find(id);
return View(albums);
}
最后是样本数据
protected override void Seed(MusicStoreEntities context)
{
var artists = new List<Artist>
{
new Artist { Name = "Aaron Copland & London Symphony Orchestra" },
etcetc
}
new List<Album>
{
new Album { Title = "ABC", Artist= artists.Single(g => g.Name == "Test")}
}
}
【问题讨论】:
-
调试 - 在返回 View(albums) 语句时停止。专辑长什么样?它对艺术家和流派有价值吗?
-
是的,值是从一个类中获取的,假设代表一个数据库。
-
您需要发布更多代码 - 您发布的内容没有任何问题,如果您在调试时弹出了 albums.Artist.Name,那么您应该不会收到您报告的错误。专辑类是什么样的?专辑呢?
标签: c# .net asp.net-mvc