EF Core - Can we specify the entity set to be queried dynamically in Linq?

Viewed 33

The app I'm building handles devices that are rented out by the company to distributors. The distributors then rent them out to charities (known internally as causes).

I'm trying to write a Linq query that will give me a list of rentals. These can either be distributor rentals or cause rentals. In either case, the query is to return a list of Rental objects, where Rental is a DTO.

I have the query below, but as you can see, there is a lot of repetition.

Rentals = string.IsNullOrWhiteSpace(DistributorId)
  ? (await AppDbContext.DistributorRentals.Include(dr => dr.Device).Include(dr => dr.Distributor)
    .OrderBy(dr => dr.Start)
    .ToListAsync())
  .Where(dr => IsRentedOnDate(dr.Device, startOfMonth) || dr.Start >= startOfMonth)
  .Select(dr => new Rental {
    Start = dr.Start,
    End = dr.End,
    Device = dr.Device.SerialNumber,
    Recipient = dr.Distributor.Name
  })
  .ToObservableCollection()
  : (await AppDbContext.CauseRentals.Include(cr => cr.Device).Include(cr => cr.Cause)
    .Where(cr => cr.DistributorRental.DistributorId == DistributorId)
    .OrderBy(cr => cr.Start)
    .ToListAsync())
  .Where(cr => IsRentedOnDate(cr.Device, startOfMonth) || cr.Start >= startOfMonth)
  .Select(cr => new Rental {
    Start = cr.Start,
    End = cr.End,
    Device = cr.Device.SerialNumber,
    Recipient = cr.Cause.Name
  })
  .ToObservableCollection();

I'm wondering if it's possible to reduce this. The only real differences are...

  1. The DbSet being queried, which is either Distributors or Causes, depending on whether the DistributorId property has a value
  2. The second Includes are different
  3. The cause query includes a Where to get rentals just for that distributor, whereas the distributor query does not need this
  4. The recipient property in the final Select uses either the Distributor or Cause as appropriate.

Any suggestions as to how I could reduce the repetition in this code?

0 Answers
Related