EF Core include an ICollection with a filter on the collection's referenced object

c# entity-framework entity-framework-core linq

Question

I need a query that will return all Drivers including the Departures collection for each, where each collection is filtered by properties of the Departure.

This query:

// id supplied by HTTP POST
var driver = await _context.Drivers
  .Include(d => d.Departures.Where(dd => dd.Acknowledged == false))
  .SingleOrDefaultAsync(m => m.ID == id);

Generates an error:

InvalidOperationException: The property expression 'd => {from Departure dd in d.Departures where ([dd].Acknowledged == False) select [dd]}' is not valid. The expression should represent a property access: 't => t.MyProperty'. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.

What am I not understanding?

Model

  • Driver has many Departures
  • Departure has one Driver

Driver:

public class Driver
{
    public int ID { get; set; }
    ...
    public virtual ICollection<Departure> Departures { get; set; }
}

Departure:

public class Departure
{
    public int ID { get; set; }
    public Boolean Acknowledged { get; set; }
    ...
    public int DriverID { get; set; }
    public virtual Driver Driver { get; set; }
}

Using EF Core 2.0 with VS Studio for Mac.

1
1
11/22/2017 2:54:06 PM

Accepted Answer

You can configure a Query Filter in your DbContext.

modelBuilder.Entity<Administrator>()
            .HasQueryFilter(admin => !EF.Property<boolean>(admin, "IsDeleted"));

should do the trick

Reference link: https://docs.microsoft.com/en-us/ef/core/querying/filters

6
11/22/2017 7:43:59 PM

Popular Answer

You should change the inner condition using Any instead of Where, as:

.Include(z => z.WorkPlaces)
.Where(x => x.WorkPlaces.Any(y => !y.IsDeleted))


Related Questions





Related

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