简体   繁体   中英

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

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')'

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM