【问题标题】:LINQ to Entities does not recognize the method 'Int32 Last[Int32]LINQ to Entities 无法识别方法“Int32 Last[Int32]”
【发布时间】:2023-04-01 12:20:01
【问题描述】:

这有什么问题?

int folderid = (from p in db.folder where p.isDefault == true select p.id).Last();

我得到这个错误

   LINQ to Entities does not recognize the method 'Int32 Last[Int32]
    (System.Linq.IQueryable`1[System.Int32])' method, and this method cannot be 
translated into a store expression.

【问题讨论】:

    标签: asp.net linq linq-to-sql


    【解决方案1】:

    Linq 无法将Last() 转换为任何有效的 sql 语句。所以我的建议是orderby decendingTake(1)

    可能是这样的:

    int? folderid =(
            from p in db.folder 
            where p.isDefault == true 
            orderby p.id descending
            select p.id
        ).Take(1).SingleOrDefault();
    

    我不知道该选择哪个,因此您可能必须将 orderby p.id descending 更改为适合您的内容。

    【讨论】:

    • 如果集合为空,FirstOrDefault() 不会将其炸毁。但我仍然 +1,这是正确的方法。
    • 你不觉得Single()SingleOrDefault() 在这里会更直观吗?
    • 如果集合为空,将抛出异常。是真的吗?
    • 是的,我认为Single() 如果他期望值。如果它可以为空,那么我会推荐SingleOrDefault()。感谢您指出。
    猜你喜欢
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多