LINQ到实体无​​法识别方法最后。真? [英] LINQ To Entities does not recognize the method Last. Really?

查看:86
本文介绍了LINQ到实体无​​法识别方法最后。真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此查询:

    public static IEnumerable<IServerOnlineCharacter> GetUpdated()
    {
        var context = DataContext.GetDataContext();
        return context.ServerOnlineCharacters
            .OrderBy(p => p.ServerStatus.ServerDateTime)
            .GroupBy(p => p.RawName)
            .Select(p => p.Last());
    }

我不得不切换到这为它工作。

I had to switch it to this for it to work

    public static IEnumerable<IServerOnlineCharacter> GetUpdated()
    {
        var context = DataContext.GetDataContext();
        return context.ServerOnlineCharacters
            .OrderByDescending(p => p.ServerStatus.ServerDateTime)
            .GroupBy(p => p.RawName)
            .Select(p => p.FirstOrDefault());
    }

我甚至不能使用 p.First(),以反映第一个查询。

为什么有这样的基本局限在什么,否则这样一个强大的ORM系统?

Why are there such basic limitations in what's otherwise such a robust ORM system?

推荐答案

这限制归结到最终还是到翻译查询的事实 SQL 和SQL有一个 SELECT TOP (以T-SQL)而不是选择底(没有这样的事)。

That limitation comes down to the fact that eventually it has to translate that query to SQL and SQL has a SELECT TOP (in T-SQL) but not a SELECT BOTTOM (no such thing).

有它周围有一个简单的方法,虽然,只是降序排列,然后做一个第一(),这是你做了什么。

There is an easy way around it though, just order descending and then do a First(), which is what you did.

编辑:
其他供应商可能会有 SELECT TOP 1 ,甲骨文它很可能是更多的东西像 WHERE ROWNUM = 1

Other providers will possibly have different implementations of SELECT TOP 1, on Oracle it would probably be something more like WHERE ROWNUM = 1

编辑:

另一种低效率的替代方案 - 我不建议这样做 - !是调用 .ToList()在<$ C上的数据C>。去年(),这将立即执行LINQ到实体已经建至该点前pression,然后你的。去年()会工作,因为在这一点上在。去年()有效的的LINQ到对象防爆pression而不是上下文中执行。 (正如你指出的,它可以带回数千条记录,这将永远不会使用的CPU物化对象的废物量)

Another less efficient alternative - I DO NOT recommend this! - is to call .ToList() on your data before .Last(), which will immediately execute the LINQ To Entities Expression that has been built up to that point, and then your .Last() will work, because at that point the .Last() is effectively executed in the context of a LINQ to Objects Expression instead. (And as you pointed out, it could bring back thousands of records and waste loads of CPU materialising objects that will never get used)

同样,我不会推荐这样做第二次,但它确实有助于说明其中执行LINQ前pression时的区别。

Again, I would not recommend doing this second, but it does help illustrate the difference between where and when the LINQ expression is executed.

这篇关于LINQ到实体无​​法识别方法最后。真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆