1
我一直在努力做到在asp.net网站上找到MVC 3音乐商店教程。 在下面的代码我试图使用LINQ到实体查询到结果返回给我从storeController浏览视图,但是当我浏览到浏览页面我收到此错误: 实体或复杂类型“MvcMusicStore.Models。类型”不能在LINQ被构造为实体查询。当我使用Lambda表达式,它们在教程中使用,但我更喜欢使用LINQ查询Linq To Entites错误:实体或复杂类型....不能在LINQ to Entities查询中构建
下面的代码工作。请有人向我解释为什么这不起作用使用下面的代码?
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>
非常感谢 绝望戴夫
我觉得这个我试过前面。我会给这个镜头并回复给你,谢谢你回答 – davey 2011-04-05 21:51:45
同意。如果我记得正确,Linq to EF中不允许进行投影。 – neontapir 2011-04-05 22:09:22
@neon:投影是允许的,但你不能投影到映射实体。 – 2011-04-05 22:10:10