I want to get one boat item from the Boat
table only if that boat is not in the RentBoat
table and has a value on the IsOnRent
column set to true.
This is my code so far:
db.Boats.SingleOrDefault(x => !db.RentBoats.Any(s => s.BoatID == x.BoatID && s.IsOnRent == true));
The error I am getting is:
The sequence contains several elements
Where is my code wrong? Any help would be great.
Essentially I want what this query does but I want it to return the matched item from an Id or return null.(a singel item not a list)
db.Boats.Where(boat => !db.RentBoats.Any(x => x.BoatID == boat.BoatID && x.IsOnRent == true)).ToList();
public class Boat
{
[Key]
public int BoatID { get; set; }
public string BoatName { get; set; }
}
public class RentBoat
{
[Key]
[Required]
public int RentBoatID { get; set; }
[ForeignKey("Boat")]
public int BoatID { get; set; }
public string BoatName { get; set; }
public bool IsOnRent { get; set; }
public virtual Boat Boat { get; set; }
}
EDIT
This is how I solved it in the end:
using (var db = new BoatContext())
{
List<RentBoat> IsBoatRented = db.RentBoats.Where(x => x.BoatID == boatId && x.IsOnRent == true).ToList();
if (IsBoatRented.Count() == 0)
{
returnedBoat = db.Boats.FirstOrDefault(x => x.BoatID == boatId);
}
}
I know it isn't as efficient or good looking as one single query. But couldn't make this with one query. If somebody can rewrite these queries to one query. Fell free to help. I would appreciate it.