我一直在拉我的头发试图做MVC 3音乐商店教程在asp.net网站上找到。在下面的代码中,我试图使用Linq到实体查询从storeController返回结果到我的浏览视图,但当我导航到浏览页面时,我收到此错误:实体或复杂类型"MvcMusicStore.Models"。不能在LINQ到实体查询中构造类型。
当我使用他们在教程中使用的Lambda表达式时,下面的代码可以工作,但我更喜欢使用Linq查询。请有人向我解释为什么使用以下代码不工作?
Storecontoller.cs
MusicStoreEntities storeDB = new MusicStoreEntities();
public ActionResult Browse(string genre)
{
//working code used in tutorial
//var genreModel = storeDB.Genres.Include("Albums")
//.Single(g => g.Name == genre);
storeDB.Genres.Include("Albums");
var genreModel = from p in storeDB.Genres
where p.Name == genre
select new Genre
{
GenreId = p.GenreId,
Name = p.Name,
Description = p.Description,
Albums = p.Albums
};
return View(genreModel.Single());
}
Genre.cs
using System.Collections.Generic;
namespace MvcMusicStore.Models
{
public class Genre
{
public int GenreId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Album> Albums { get; set; }
}
}
MusicStoreEntities.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcMusicStore.Models
{
public class MusicStoreEntities : DbContext
{
public DbSet<Album> Albums { get; set; }
public DbSet<Genre> Genres { get; set; }
}
}
browse.cshtml
<h2>Browsing Genre: @Model.Name</h2>
<ul>
@foreach (var album in Model.Albums)
{
<li>
@album.Title
</li>
}
</ul>
多谢绝望的戴夫
你必须使用这个:
var genreModel = from p in storeDB.Genres.Include("Albums")
where p.Name == genre
select p;
return View(genreModel.Single());
Include
必须是查询的一部分。提前打电话是行不通的。你可以这样做:
var query = storeDB.Genres.Include("Albums");
var genreModel = from p in query
where p.Name == genre
select p;
你也不能创建投影到实体类(new Genre
)。