LINQ to Entities不认识方法'Int32 Last[Int32]'

3
这有什么问题吗?
int folderid = (from p in db.folder where p.isDefault == true select p.id).Last();

i get this error

   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.
1个回答

7
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()不会出错。但是我还是给你点赞,这是正确的方法。 - Wiktor Zychla
дҪ дёҚи§үеҫ—еңЁиҝҷйҮҢдҪҝз”ЁSingle()жҲ–иҖ…SingleOrDefault()жӣҙеҠ зӣҙи§Ӯеҗ—пјҹ - MarcinJuraszek
如果集合为空,将抛出异常。这是真的吗? - MHF
是的,我认为如果他期望一个值,那么使用 Single()。如果它可能为空,则建议使用 SingleOrDefault()。感谢指出这一点。 - Arion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接