2013-04-27 67 views
0

考慮下表:需要SQL語句轉換成實體框架相當於

InstrumentLogs

InstrumentLogId (PK, int, not null) 
InstrumentId (FK, int, not null) 
LogDate (datetime, not null) 
Action (string, not null) 

儀器

InstrumentId (PK, int, not null) 
CountyId (FK, int, not null) 

CountyId (PK, int, not null) 
StateFips (FK, int, not null) 
Name (string, not null) 

美國

StateFips (PK, int, not null) 
Name (string, not null) 

我需要弄清楚如何編寫使用實體框架此SQL查詢:

select s.StateName, count(*) as total 
from instruments as i 
join counties as c on i.CountyID = c.CountyID 
join states as s on s.StateFIPS = c.StateFIPS 
where i.InstrumentID in 
    (select i1.InstrumentId from InstrumentLogs as i1 where i1.action = 'review' and 
    i1.logdate in (select max(logdate) from instrumentlogs as i2 where i1.instrumentid 
    =i2.InstrumentID group by i2.instrumentid)) 
group by s.StateName 

我試過的東西沿着線:

_context.Instruments.Include(i => i.County.State) 
    .Where(i => _context.Logs.Where(l => l.Action == 'review' 
    && _context.Logs.Where(l2 => l2.InstrumentId == l.InstrumentId).Max(l2 => l2.LogDate) == l.LogDate).GroupBy(i => i.County.State.Name) 
    .Select(g => new { State = g.Key.Name, Total = g.Count() }); 

但是,EF不會l這個。我結束了錯誤,指出只支持原始類型或枚舉類型。

感謝您的幫助。

回答

0

我終於得到它像這樣

 var _query = _dataContext.IndexLogs.GroupBy(l => l.InstrumentId, l => l) 
      .Select(grp => new { Id = grp.Key, Date = grp.Max(g => g.ActionDate) }); 

     //Prequery to find log records that match given type and action type 
     var _indexes = _dataContext.IndexLogs.Where(l => l.Action == type 
      && _query.Contains(new { Id = l.InstrumentId, Date = l.ActionDate})).Select(i => i.InstrumentId); 


     var _states = _dataContext.AdvancedIndexes 
      .Include(i => i.County.State) 
      .Where(a => a.Id > 0 && _indexes.Contains(a.Id)) 
      .GroupBy(i => new { i.County.State.Id, i.County.State.Name }) 
      .Select(g => new { fips = g.Key.Id, name = g.Key.Name, count = g.Count() }); 
工作