gpt4 book ai didi

c# - 在 C# 中使用 AsQueryable 查询时获取 InvalidOperationException

转载 作者:可可西里 更新时间:2023-11-01 10:28:49 25 4
gpt4 key购买 nike

我有一个名为 City 的实体类。

 [BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string _id { get; set; }
public string city { get; set; }
public Array loc { get; set; }
public double pop { get; set; }
public string state { get; set; }

我想用 AsQueryable() 类创建一个简单的查询。这是我的查询代码

string dbName = dao.dbName();
var db = mongo.GetDatabase(dbName);

using (mongo.RequestStart(db))
{
var collection = db.GetCollection<City>("city");
var query = collection.AsQueryable().First(c => c.city.Equals("VIENNA"));

Console.WriteLine( query.ToString());
}

当我运行代码时,我得到一个 System.InvalidOperationException 像这样

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll

var query = collection.AsQueryable().First(c => c.city.Equals("VIENNA"));

行。谁能解释为什么我会收到此异常并找到解决方案?

最佳答案

First方法查找与作为参数传递的表达式匹配的第一个结果。当它找不到任何东西时,它会抛出这个异常。如果您不确定该序列是否包含您要查找的元素,请使用 FirstOrDefault .参见 this一篇很好的总结文章。

关于c# - 在 C# 中使用 AsQueryable 查询时获取 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30117376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com