我正在尝试优化LINQ to SQL请求,以便生成单个SQL语句。目前我有这样的事情:
编辑:为了清晰起见,删除了“where”过滤器 - 同样“Id”是两个对象类型的databsse中的主键
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();
酒店业务级别类定义为:
public class Hotel
{
public int Id { get; set; }
public string Name { get; set; }
public List<HotelRoom> Rooms { get; set; }
}
其中查询使用初始值设定项在执行查询时从DataContext实体动态创建 business 对象。
问题是,很明显,Rooms集合上的.ToList()
会导致通过第二个查询填充Hotel.Rooms集合。
有没有办法用所有的HotelRooms填充Hotel.Rooms属性,而不会产生额外的查询?
答案 0 :(得分:0)
//grab the rows from the database in direct fashion.
var joinedRows =
(
from h in db.Hotels
where h.Name == name
from hr in h.HotelRooms
select new {HotelRow = h, HotelRoomRow = hr}
)
.ToList();
//shape the data locally
List<Hotel> result =
from row in joinedRows
group row.HotelRoomRow by row.HotelRow into g
let h = g.Key
select new Hotel()
{
Id = h.Id,
Name = h.Name,
Rooms = (
from r in g
select new HotelRoom()
{
Id = r.Id,
Code = r.Code,
Category = r.Category
}).ToList()
};