简体   繁体   中英

LINQ nested query issue - System.NotSupportedException

I'm trying to reproduce the following SQL query in LINQ:

select *
  from dbo.events_log 
 where std_datetimeseq < '2014011523:49:00001'
   and logname in ('S', 'D', 'O')
   and std_datetimeseq = (
       select min(std_datetimeseq)
         from dbo.events_log
        where std_datetimeseq < '2014011523:49:00001'
          and logname in ('S', 'D', 'O'))

This is what I have:

from e in _context.EventLogs
                    where e.std_datetimeseq.CompareTo(stdDateTimeSeq) < 0
                      && eventMessage.Content.EquipToSearch.Contains(e.logname)
                      && e.std_datetimeseq.CompareTo(
                      ((from e2 in _context.EventLogs
                        where e2.std_datetimeseq.CompareTo(stdDateTimeSeq) < 0
                            && eventMessage.Content.EquipToSearch.Contains(e2.logname)
                        select e2).Min().std_datetimeseq)) == 0
                           select e

I keep getting this exception:

{"The specified method 'MyEntityModel.EventLog Min[EventLog](System.Linq.IQueryable`1[HDSREntityDataModelNS.EventLog])' 
on the type 'System.Linq.Queryable' cannot be translated into 
a LINQ to Entities store expression because no overload matches the passed arguments."}

I have no idea what's wrong.

eventMessage.Content.EquipToSearch is a List with "S", "D", "O" in it. The LINQ is going against entity framework.

Thanks

The problem is with the sub query

(from e2 in _context.EventLogs
 where e2.std_datetimeseq.CompareTo(stdDateTimeSeq) < 0
    && eventMessage.Content.EquipToSearch.Contains(e2.logname)
 select e2).Min().std_datetimeseq

In order to get the min std_datetimeseq value you have to select it, otherwise you are trying to find the minimum EventLogs item which not only doesn't make sense, but cannot be translated to SQL by EF. Instead do the following.

(from e2 in _context.EventLogs
 where e2.std_datetimeseq < stdDateTimeSeq
    && eventMessage.Content.EquipToSearch.Contains(e2.logname)
 select e2.std_datetimese).Min()

On a side note your query will be easier to read if you just use the comparison operators instead of CompareTo as suggested by Servy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM