Search code examples
linqentity-frameworklinq-to-entitiesef-code-firstef4-code-only

how do I write this SQL in LINQ Entity Framework 4


select C.CenterID
from   dbo.Center C 
 inner join (select PersonID, max(EffectiveDate) as EffectiveDate
         from   Center
         where  EffectiveDate <= getdate()
         group by PersonID) as C2 
 on C.PersonID= C2.PersonID
  and C.EffectiveDate = C2.EffectiveDate

Center table has an PersonID and EffectiveDate, multiple records have the same PersonID, but different EffectiveDates, I'm trying to return the 1 most current record for each PersonID

ideally, I want to express this in linq as IQueryable so that I can use it to build larger queries.


Solution

  • var q = from c in oc.Center
    join c2 in (
      from ci in oc.Center
      where ci.EffectiveDate <= DateTime.Now
      group ci by ci.PersonID into cig
      select new { PersonID = cig.Key, EffectiveDate = cig.Max(ed => ed.EffectiveDate) }
     ) on new { c.PersonID, c.EffectiveDate } equals { c2.PersonID, c2.EffectiveDate }
    select c.CenterID