can I get a hand converting the following into a LINQ statement.
SELECT reports.* FROM [dbo].[ReportLists] rl INNER JOIN [dbo].[ReportItems] ri ON rl.Id = ri.ReportListId INNER JOIN [dbo].[Reports] reports ON ri.Id = reports.ReportItemId WHERE reports.createdDate IN ( SELECT MAX(report_max_dates.createdDate) FROM [dbo].[Reports] report_max_dates GROUP BY report_max_dates.seedLot )
Currently I have it down to this:
db.ReportLists.Select(rl => db.ReportItems .Where(ri => ri.ReportListId == rl.Id) .Select(ri => db.Reports .Where(r => r.ReportItemId == ri.Id) .GroupBy(r => new { r.seedLot }) .Select(g => g.OrderByDescending(x => x.createdDate).FirstOrDefault())));
The problem with the LINQ above is that it returns entries that have titles changed. Within the database I keep history of all records (hence the need for the first on the createdDate order descending. When I change a report from title x to title y, it shows up under both titles when I only want the most recent record which would hence be the one under title y.
EDIT Sorry for the lack of detail. I have a reports table which holds info about the report (seedlot being an identifier). Whenever a report is edited, a new record is inserted (vs updating the old one) such that history is kept. In this case then the max entry for the createdDate indicates that the report is the most recent record to be displayed. Reports are then grouped into titles or ReportItems. These report items hold the title and associated reports. These reportItems are held in a ReportList such that I can print out the JSON in a desired format and just contains a status column and id linked to by the ReportItems.
In the event that a report is moved from title a to title b, a new record is entered with the title foreign key linking up to the title it was changed to. When this happens the above given LINQ returns the record under each individual ReportItem when it should only return the newest entry for title b (from the example above). Other than this the LINQ statement only returns the most recent record for the createdDate.
Here are my class structures (which mimic the DB structure as well)
public class ReportList { public int Id {get;set;} public string status {get;set;} public List<ReportItem> {get;set;} } public class ReportItem { public int Id {get;set} public string title {get;set;} public List<Report> {get;set;} } public class Report { public int Id {get;set;} public string Lot {get;set;} ... Other data ... public DateTime createdDate {get;set;} }
Thanks, Dman