从数据库中抓取某些数据

时间:2016-06-01 13:42:15

标签: entity-framework

我正在努力从我的数据库中获取一些数据

我的数据库设计是这样的:我有一个酒店有一个hotelchainid,一个有hotelid的建筑,一个有建筑物的地板和一个有地板的房间。

我正试图抓住数据库中某个酒店的所有房间

Databasehandler.cs方法:

        public static List<Room> GetAllRoomsByHotel(string hotelname)
        {
        HotelDbContext context = new HotelDbContext();

        var hotel = context.Hotels.Where(h => h.Name == hotelname).Single();
        var buildings = context.Buildings.Where(b => b.Hotel.HotelID == hotel.HotelID).ToList();
        var floors = context.Floors.Where(f => f.Building.BuildingID == buildings.BuildingID).ToList();
        var rooms = context.Rooms.Where(r => r.Floor.FloorID == floors.FloorID).ToList();

        return rooms;
        }

我正在考虑将找到的对象添加到List并循环遍历该列表以获取id并在之后比较它们但我不知道如何实现它以及是否可行。

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

一旦您拥有了所有导航属性,就可以实现您想要的目标

context.Hotels.Where(h => h.Name == hotelname)
              .SelectMany(h => h.Buildings)
              .SelectMany(b => b.Floors)
              .SelectMany(f => f.Rooms)

这将为您提供属于hotelname指定的酒店的房间集合。

通常,尤其是使用SelectMany,查询语法更容易......

from h in context.Hotels where h.Name == hotelName
from b in h.Buildings
from f in b.Floors
from r in f.Rooms
select new
{
    Hotel = h.Name,
    Building = b.Name,
    Floor = f.Number,
    Room = r.Number
}

...因为,如您所见,如果需要,可以更容易在最终结果中包含父数据。

相关问题