I am trying to optimize a LINQ to SQL request so that it results in a single SQL statement. At the moment i have something like this:
EDIT : removed the "where" filter for clarity - also "Id" is a primary key in the databsse for both object types
hotel = (from h in db.Hotels
let rooms = (from r in db.HotelRooms
where r.HotelId == h.Id
select new HotelRoom
{
Id = r.Id,
Code = r.Code,
Category = r.Category
})
select new Hotel
{
Id = h.Id,
Name = h.Name,
Rooms = rooms.ToList()
}).FirstOrDefault();
Where the Hotel business level class is defined as:
public class Hotel
{
public int Id { get; set; }
public string Name { get; set; }
public List<HotelRoom> Rooms { get; set; }
}
Wherein the query is using initializers to create business objects on the fly from the DataContext entities as the query is executed.
The problem is that obviously the .ToList()
on the Rooms collection causes the Hotel.Rooms collection to be populated via a second query.
Is there a way to populate the Hotel.Rooms property with all the HotelRooms, without it generating additional queries?