Linq:当object为null时,抛出异常

时间:2013-11-19 14:52:28

标签: c# asp.net linq

我对查询有困难。

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,

1 个答案:

答案 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();