Need some help on a Linq query, 3rd level include where

blazor c# entity-framework-core linq

Question

I've scoured the internet but not been able to find something for my specific case.

Here's my models:

    public class Unit
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UnitID { get; set; }
    public string Name { get; set; }
    public int UnitStatusID { get; set; }
    public List<ReservationUnit> ReservationUnits { get; set; }

}

public class ReservationUnit 
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ReservationUnitID { get; set; }

    [Required]
    public int ReservationID { get; set; }
    public Reservation Reservation { get; set; }

    [Required]
    public int UnitID { get; set; }
    public Unit Unit { get; set; }

    public decimal Amount { get; set; }
    public bool AmountIsTaxInclusive { get; set; }
    public bool IsFixedRate { get; set; }
}

public class Reservation
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ReservationID { get; set; }

    public int ReservationStatusID { get; set; }

    public List<ReservationUnit> Units { get; set; }

}

I need to find:

  • All units with statusid == 1
  • For all those units, all reservations with reservationid == 1

I can get the units and I can select all the reservationunits... but I can't filter the reservations of get the item of reservation included. Could anyone point me in the right direction? This is what I've tried:

var unitQuery = 
                db
                .Units
                .Where(x => x.UnitStatusID == 1 || x.UnitStatusID == 4)
                .Include(o => o.ReservationUnits.Where(p => p.Reservation.ReservationStatusID == 1))
                .ToList();

which is giving me the following error:

System.ArgumentException: 'The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. (Parameter 'path')'

1
1
4/12/2020 6:48:41 PM

Accepted Answer

It seems that this worked for me.

var unitQuery =
                db
                .Units
                .Include("ReservationUnits.Reservation")
                .Where(x => x.UnitStatusID == 1 || x.UnitStatusID == 4)
                .Where(x => !x.ReservationUnits.Any() || x.ReservationUnits.Any(o => o.Reservation.ReservationStatusID == 1 || o.Reservation.ReservationStatusID == 2))
                ;

Does this look correct?

1
4/12/2020 7:10:17 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow