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...
- The
DbSetbeing queried, which is eitherDistributorsorCauses, depending on whether theDistributorIdproperty has a value - The second
Includes are different - The cause query includes a
Whereto get rentals just for that distributor, whereas the distributor query does not need this - The
recipientproperty in the finalSelectuses either theDistributororCauseas appropriate.
Any suggestions as to how I could reduce the repetition in this code?