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