开发者

Linq To Entites error: The entity or complex type .... cannot be constructed in a LINQ to Entities query

I have been pulling my hair out trying to do the MVC 3 Music Store tutorial found on the asp.net website. In the below code I am trying to use a Linq to Entities query to return results to my Browse view from the storeController but I receive this error when I navigate to the browse page: The entity or complex type 'MvcMusicStore.Models.Genre' cannot be constructed in a LINQ to Entit开发者_运维技巧ies query.

The code below works when I use the Lambda expression that they use in tutorial but I am more comfortable using a Linq Query. Please can someone explain to me why this doesn’t work using the following code?

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>

Many thanks desperate dave


You must use this:

var genreModel = from p in storeDB.Genres.Include("Albums")
                 where p.Name == genre
                 select p;
return View(genreModel.Single());

Include must be part of query. Calling it in advance doesn't work. You can do this:

var query = storeDB.Genres.Include("Albums");
var genreModel = from p in query
                 where p.Name == genre
                 select p;

Also you can't create projection to entity class (new Genre). You must select it directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜