我对查询有困难。
string userId = User.Identity.GetUserId();
var houseViewModel = this.Data.Houses.All()
.Where(u => u.UserId == userId && u.Name == houseName)
.Select(h => new HouseViewModel
{
Id = h.Id,
Name = h.Name,
ImageUrl = h.ImageUrl,
FloorsViewModel = h.Floоrs.Where(f=>f.Id>0)
.Select(f => new FloorViewModel
{
Name = f.Name,
RoomViewModel = f.Rooms.Where(r => r.Id > 0)
.Select(r => new RoomViewModel
{
Id = r.Id,
Name = r.Name,
SensorViewModel = new SensorViewModel
{
Id = r.Sensor.Id,
CurrentTemp = r.Sensor.CurrentTemp,
},
})
})
})
.SingleOrDefault();
当他来到没有传感器抛出异常的房间时,因为Id
SensorViewModel
是一个不可为空的属性。
SensorViewModel = new SensorViewModel
{
Id = r.Sensor.Id,
答案 0 :(得分:7)
SensorViewModel = r.Sensor == null ? new SensorViewModel() : new SensorViewModel
{
Id = r.Sensor.Id,
CurrentTemp = r.Sensor.CurrentTemp,
},
接下来试试。只选择带传感器的房间。
RoomViewModel = f.Rooms.Where(r => r.Id > 0 && r.Sensor != null)
.Select(r => new RoomViewModel
{
Id = r.Id,
Name = r.Name,
SensorViewModel = new SensorViewModel
{
Id = r.Sensor.Id,
CurrentTemp = r.Sensor.CurrentTemp,
},
})
最后一次尝试,从EF中选择数据到列表中然后制作viewmodel
var house = this.Data.Houses.All()
.Where(u => u.UserId == userId && u.Name == houseName).ToList();
var houseViewModel = house.Select(h => new HouseViewModel
{
Id = h.Id,
Name = h.Name,
ImageUrl = h.ImageUrl,
FloorsViewModel = h.Floоrs.Where(f=>f.Id>0)
.Select(f => new FloorViewModel
{
Name = f.Name,
RoomViewModel = f.Rooms.Where(r => r.Id > 0)
.Select(r => new RoomViewModel
{
Id = r.Id,
Name = r.Name,
SensorViewModel =r.Sensor == null ? null : new SensorViewModel
{
Id = r.Sensor.Id,
CurrentTemp = r.Sensor.CurrentTemp,
},
})
})
})
.SingleOrDefault();