我正在尝试将三个不同表的计数与专辑列表一起传递到视图中。它是 MvcMusicStore 教程的一个模组。我收到“ObjectContext 实例已被处置,无法再使用...”错误。我知道它与延迟加载有关,但我不知道如何使它工作。
// Controller
public class StoreManagerController : Controller
{
private MusicStoreDBEntities context = new MusicStoreDBEntities();
public ActionResult Index()
{
// counts
ViewData["artistCount"] = context.Artists
.Select(e => new { e.ArtistId }).Count();
ViewData["genreCount"] = context.Genres
.Select(e => new { e.GenreId }).Count();
ViewData["albumCount"] = context.Albums
.Select(e => new { e.AlbumId }).Count();
// also tried two other ways...same result.
//ViewData["artistCount"] = context.Artists
.Select(e => new { e.ArtistId }).ToList().Count;
//ViewData["artistCount"] = context.Artists
.Select(e => new { e.ArtistId }).ToList().Count();
// album list
var albums = context.Albums.Include(a => a.Genre).Include(a => a.Artist);
return View(albums.ToList());
}
}
// View - Index.cshtml
@model IEnumerable<MVC_App1.Models.Album>
<div>
<label><strong>Database Counts:</strong></label>
Albums: @ViewData["albumCount"] ...
Artists: @ViewData["artistCount"] ...
Genres: @ViewData["genreCount"]
</div>
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Artist.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.AlbumArtUrl)
</td>
</tr>
}
</table>
解决方案:
所以我接受了添加新模型的建议。
public class AlbumsCollection
{
public IEnumerable<Album> Albums = new List<Album>();
public IEnumerable<Artist> Artists = new List<Artist>();
public IEnumerable<Genre> Genres = new List<Genre>();
}
然后在视图中进行计数。我意识到无论如何我都在将整个专辑列表传递给视图,所以那里并没有放缓。对于艺术家和流派……反正不会有很多,因为它们是一对多的关系。我想这是放弃在控制器中进行计数....但我想这已经足够好了。