开发者

Linq with subquery with Let

What I'm trying to get from this Linq query is a list of all Adverts where the most recent associated Log with a LogType.IsStatus == true has a LogType.Name of either Confirmed or Renewed. To be clear, an Advert has many Logs and each Log has one LogType. So far I have the following, but it's giving me an error System.NotSupportedException on the LastOrDefault.

var adverts = (from a in database.Adverts
                      let lastLog = (from l in a.Logs
                                     where l.LogType.IsStatus == true
                                     orderby l.Created_at
                                     select l)开发者_Go百科.LastOrDefault()
                      where (lastLog != null)
                            &&
                            (lastLog.LogType.Name == "Confirmed" || lastLog.LogType.Name == "Renewed")
                            orderby a.Created_at descending
                      select a).ToList();


LastOrDefault() is not supported in LINQ to Entities (see here).

You can work around this by changing the order by clause in your let subquery to an order by descending and then use FirstOrDefault() instead.

var adverts = (from a in database.Adverts
               let lastLog = (from l in a.Logs
                              where l.LogType.IsStatus == true
                              orderby l.Created_at descending
                              select l).FirstOrDefault()
               where (lastLog != null)
                     &&
                     (lastLog.LogType.Name == "Confirmed" || lastLog.LogType.Name == "Renewed")
                      orderby a.Created_at descending
               select a).ToList();


try this

var lookingType = new string[]{"Confirmed", "Renewed"};

var result = database.Adverts
  .Where(entry 
    => entry.Logs.Count() > 0 && entry.Logs.Any(log => log.LogType.IsStatus))
  .Select(entry 
    => new { data = entry, 
       lastLog = entry.Logs.OrderByDescending(log => log.Created_at).First() 
    })
  .Where(entry => lookingType.Contains(entry.lastLog.LogType.Name))
  .Select(entry => entry.data).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜