我有一个简单的查询。

它检查房间列表-prebookedRooms

然后,它检查另一个房间列表,但使用.Except运算符从随后的列表中删除任何prebookedRooms

        // Get list of rooms already booked
        var prebookedRooms = dbt.Rooms
            .Where(room => room.Rentals.Any(rental =>
                (dteFrom >= rental.check_in && dteFrom < rental.check_out)));

        // Get list of rooms
        var rooms = dbt.Rooms.Where(r => r.h_id == AccID)
            .Except(prebookedRooms)
            .GroupBy(p => p.RoomTypes).Select(g => new RatesViewModel
            {
                TypeName = g.Key.t_name,
                TypeID = g.Key.t_id,
                TypeCount = g.Count()
            })
            .ToList();


效果很好-rooms返回房间列表,但不包括prebookedRooms

但是,如果prebookedRooms不返回任何记录(即,空的“枚举未产生任何结果”)-那么在执行第二个查询时,我会报错(var rooms = ...):

The cast to value type 'Int64' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

无论如何,在第二个查询中是否要检查prebookedRooms是否为空,所以我可以避免此错误?

prebookedRooms模型:

public class Room
{
    [Key]
    public long room_id { get; set; }
    public long hotel_id { get; set; }
    public long type_id { get; set; }
}


在VS中出现的错误是:


谢谢,

标记

最佳答案

你不能辞职并写:

    var rooms = dbt.Rooms.Where(r => r.h_id == AccID)
        .Where(room => !room.Rentals.Any(rental =>
            (dteFrom >= rental.check_in && dteFrom < rental.check_out))).
        .GroupBy(p => p.RoomTypes).Select(g => new RatesViewModel
        {
            TypeName = g.Key.t_name,
            TypeID = g.Key.t_id,
            TypeCount = g.Count()
        })
        .ToList();

10-05 19:23