This should be simple, but I’m getting confused.
I have a parent/child tables – and all I want to do, is select from the parent table, depending on filtering of the child table.
So the parent table, Rooms, is linked one to many to the clients table – I want to select rooms, where there are no linked records in the Clients table, where the clients.Departure date is before a specific date:
public class Room
{
public int RoomId { get; set; }
public string RoomName { get; set; }
public List<Client> Clients { get; set; }
}
public class Client
{
public int ClientId { get; set; }
public int RoomId { get; set; }
public string Name { get; set; }
public DateTime Arrival { get; set; }
public DateTime Departure { get; set; }
public Room Room { get; set; }
}
In my controller I have been trying:
public ActionResult Avail()
{
DateTime dteFrom = DateTime.Parse("2012-07-01"); //hard coded for testing
Room room = db.Rooms.Where(r => r.Clients.Any(c => c.Departure <= dteFrom));
But I get the error message:
Cannot implicitly convert type 'System.Linq.IQueryable<ttp.Models.Room>' to 'ttp.Models.Room'. An explicit conversion exists (are you missing a cast?)
Can anyone suggest do I need to change my model classes, or my Where statement?
Room roomrepresents a single room whereasdb.Rooms.Where(r => r.Clients.Any(c => c.Departure <= dteFrom))returns a list of rooms.If you expect your query will only return one result, you could do the following:
Or if you would like to return all the rooms that match the query, you could do the following: