ARTICLE AD BOX
Imagine the following classes (much simplified version of the real use case):
public class Driver { public Int32 Id {get;set;} public String Name {get;set;} public String Country {get;set;} public IEnumerable<Drive> Drives {get;set;} public DateTime? FirstDriveDate => this.Drives.FirstOrDefault().Min(); public DateTime? LastDriveDate => this.Drives.FirstOrDefault().Max(); } public class Drive { public Int32 Id {get;set;} public DateTime Date {get;set;} public Int32 Distance {get;set;} }In my application the 'FirstDriveDate' and 'LastDriveDate' properties play an important role, and are often visualised in the UI. But I also need them a lot in LINQ queries. In WHERE clauses, in ORDER BY clauses, and in SELECT clauses. Right now whenever I have a query that needs to use these 'properties' I just rewrite the exact linq part in the bigger query. But if in the future the 'definition' of how 'FirstDriveDate' is calculated is changed, I need to manually update all my LINQ queries as well. Is there a way I can rewrite those properties as 'Expressions' so that i can just integrate them in my queries? Especially because depending on the situation I want the logic to be executed on the database instead of first loading all objects in memory and only then apply the filter/sorting.
For example:
var topNewUKDrivers = database.GetAll<Driver>() .Where(o => o.FirstDriveDate.Year == DateTime.Today.Year && o.Country == "UK") .OrderBy(o => o.FirstDriveDate) .ThenBy(o => o.Name).ToList()Instead of:
var topNewUKDrivers = database.GetAll<Driver>() .Where(o => o.Drives.FirstOrDefault().Min().Year == DateTime.Today.Year && o.Country == "UK") .OrderBy(o => o.Drives.FirstOrDefault().Min()) .ThenBy(o => o.Name).ToList()Explore related questions
See similar questions with these tags.
