2013-02-11 131 views
-2

我需要幫助生成所需的C#代碼來實現以下SQL查詢。我不確定這是否可能?SQL到LINQ轉換

select p.Name, r.Id, r.Status, r.Created, r.DepartmentId 
from (select r.*, row_number() over (partition by personid order by created desc) as seqnum 
     from checkin r 
     where r.departmentid = '7AF20674-AEC1-4D4C-B1EA-88B1D7E8F3DB' and cast(created as date) = '2013-02-11' 
    ) r join 
    person p 
    on r.personid = p.id 
where seqnum = 1 
order by p.name desc 

之前我以前每人只有一次註冊,所以以下是可能的。現在,我可以每人每天進行多次註冊,這就是SQL更新的原因。

var query = from b in context.Persons 
       join c in context.CheckIns 
        on b.Id equals c.PersonId into JoinedPersCheck 
       from c in JoinedPersCheck.Where(i => i.Date.Equals(date)).DefaultIfEmpty() 
       where b.DepartmentId.Equals(departmentId) 
       orderby b.Name 

       select new Model.PersonCheckIn 
       { 
        CheckIn = MapToCheckInModel(c), 
        Person = MapToModel(b), 
       }; 
    return query; 
+4

還有,你試過這麼遠嗎?至少開始實施LINQ解決方案並儘可能地實現;至少處理簡單的東西。 – Servy 2013-02-11 20:46:34

+0

@Servy好吧,我用我之前使用的代碼編輯過我的帖子。我很難適應分區和row_number() – Andreas 2013-02-11 20:56:17

回答

0

試試這個:

var query = context.CheckIns 
       .Where(p => p.DepartmentId == departmentId && p.Created.Date == date) 
       .GroupBy(r => r.PersonId) 
       .Select(g => g.OrderByDescending(p => p.Created).First()) 
       .Join(context.Persons, c => c.PersonId, p => p.Id, 
         (c,p) => new { p.Name, c.Id, c.Status, c.Created, c.DepartmentId}) 
       .OrderByDescending(f => f.Name);