Link to home
Start Free TrialLog in
Avatar of websss
websssFlag for Kenya

asked on

Linq - FirstOrDefault and inner join

I have 2 tables

Groups
GroupLogs

On first load of webpage I need to just pick the firstordefault group, and load all LOGS for that GROUP

here is the query i have so far
     var _getHistoricalData = (
                    from pGroup in _mme.t_Groups
                    join pLog in _mme.t_GroupLog on pGroup.Group_ID equals pLog.fk_Groups_Id
                   where (pLog.LogTimeStamp < DateTime.Now.AddDays(-7))

Open in new window


This returns all groups and all logs
How would i select the first Group and its logs only?
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi websss;
 
The following code snippet will return the first group.
var _getHistoricalData = (
                    from pGroup in _mme.t_Groups
                    join pLog in _mme.t_GroupLog on pGroup.Group_ID equals pLog.fk_Groups_Id
                    where (pLog.LogTimeStamp < DateTime.Now.AddDays(-7)).FirstOrDefault();

Open in new window

Avatar of websss

ASKER

When adding FirstorDefault at the end, it has a red line on it:
'bool' does not contain a definition for 'FirstOrDefault' and no accessible extension method 'FirstOrDefault' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?)
You need to group the logs by group id as shown below:
 var _getHistoricalData = (from pLog in _mme.t_GroupLog
                          where (pLog.LogTimeStamp < DateTime.Now.AddDays(-7))
                          group pLog by pLog.fk_Groups_Id into g
                          select new { Group = _mme.t_Groups.FirstOrDefault( c => c.Group_ID == g.First().fk_Groups_Id), Logs = g.ToList() })
						  .FirstOrDefault();

Open in new window


To get info use:
_getHistoricalData.Group  contains group details
_getHistoricalData.Logs contains group Logs
What version of Visual Studio are you using and .Net Framework?
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.