DimitriB
DimitriB

Reputation: 1

Linq request group by

I'd like to group my request by FkOperateur and FkPstStd but I still need information in the select new part. How should I proceed to get IdPoste, FkStandard, IsValidated, Date depending on the group part result

var shortFormations =
  (from f in _context.Formations
   where f.FkPstStdNavigation.FkPosteNavigation.FkZoneNavigation.FkBatimentNavigation.IdBatiment == Batiment && (f.FkOperateurNavigation.Equipe == Equipe || Equipe == null)
   group f by new { f.FkOperateur, f.FkPstStd } into formation
   select new shortFormations
   {
       FkOperateur = formation.Key.FkOperateur,
       FkPstStd = formation.Key.FkPstStd,
       IdPoste = f.FkPstStdNavigation.FkPosteNavigation.IdPoste,
       FkStandard = f.FkPstStdNavigation.FkStandard,
       IsValidated = f.IsValidated,
       Date = f.DateFormation,
   })
   .AsNoTracking()
   .ToList(); 

I can't get IdPoste FkStandard IsValidated and Date return f doesn't exist on current context on these line.

Could you explain me please.

Select
    fk_operateur,Fk_Pst_Std, max(date_formation)
FROM
    Formations
GROUP by
    Fk_Operateur,Fk_Pst_Std

that's a try in SQL but I'm not able to get others column mentionned before

returns

fk_operateur FkPstStd date_formation
1 1 Adate

and many other rows

Upvotes: 0

Views: 44

Answers (1)

WisdomSeeker
WisdomSeeker

Reputation: 924

Since its grouped, to access the mentioned fields, you will have to look in the Values and select the correct item. As in, something like

select new shortFormations
   {
       FkOperateur = formation.Key.FkOperateur,
       FkPstStd = formation.Key.FkPstStd,
       IdPoste = formation.FirstOrDefault()
                    .FkPstStdNavigation.FkPosteNavigation.IdPoste,
       ....

or order it and then select the correct record

Upvotes: 1

Related Questions