Why does this linq query fail when I change the select clause to select new Model

ado.net-entity-data-model asp.net-mvc-5 c# entity-framework-6 linq

Question

Why does this premise hold up:

var rooms = from m in db.Rooms
                      where
                      m.FK_HotelID == id
                      select m;

            return View(rooms.ToList());

yet this query (which I created using a tool called "Linqer") seems to be unsuccessful?

var rooms = from m in db.Rooms
                      where
                      m.FK_HotelID == id
                      select new Room
                      {
                          RoomID = m.RoomID,
                          RoomNumber = m.RoomNumber,
                          RoomType = m.RoomType,
                          FK_HotelID = m.FK_HotelID
                      };

            return View(rooms.ToList());

Help is needed for the query to return aList of Room objects. Since the query needs objects of the type, I don't believe I can use an anonymous type or a DTO Model.Room . However, when I attempt to obtain this view in my VS2013 Project, I get the following error message: The query does yield results in the Linqer software.

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code.

Additional information: The entity or complex type 'HotelApp.Models.Room' cannot be constructed in a LINQ to Entities query.

P.S. For your reference, here is my Room class:

public partial class Room
{
    public Room()
    {
        Bookings = new HashSet<Booking>();
    }
    public int RoomID { get; set; }
    public int RoomNumber { get; set; }
    public string RoomType { get; set; }
    public int? FK_HotelID { get; set; }
    public virtual ICollection<Booking> Bookings { get; set; }
    public virtual Hotel Hotel { get; set; }
}
1
1
11/27/2017 7:52:18 AM

Accepted Answer

ZZZ_tmp
2
11/27/2017 9:35:53 AM

Popular Answer

That's whyRoom is one of your mapped entities, and you are not permitted to project to a mapped entity. You must project to an anonymous type or utilise a DTO.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow