I have a simple query.
It checks for a list of rooms - prebookedRooms
It then checks for another list of rooms, but uses the .Except
operator, to remove any prebookedRooms
from the subsequent list:
// 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();
This works fine - with rooms
returning a list of rooms, with prebookedRooms
excluded.
However, if prebookedRooms
doesn't return any records (ie. Empty "Enumeration yielded no results") - then I get an error when executing the second query (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.
Is there anyway of checking if prebookedRooms is empty, within the second query, so I can avoid this error?
prebookedRooms model:
public class Room
{
[Key]
public long room_id { get; set; }
public long hotel_id { get; set; }
public long type_id { get; set; }
}
The error as it appears in VS is:
Thank you,
Mark
dbt.Rooms.Where(r => r.h_id == AccID).Except(prebookedRooms)
isn't null before trying the.GroupBy
? – ChrisFExcept
you can check it's not null before doing theGroupBy
. – ChrisF