在 C# 中使用 AsQueryable 查询时获取 InvalidOperationException
getting InvalidOperationException while querying with AsQueryable in C#
我有一个实体 class 作为城市。
[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() class 创建一个简单的查询。这是我的查询代码
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 method looks for the first result that matches the expression passed as argument. When it doesn't find any, it will throw this exception. If you are not sure that the sequence contains the element you are looking for, use FirstOrDefault. See this 文章进行了很好的总结。
我有一个实体 class 作为城市。
[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() class 创建一个简单的查询。这是我的查询代码
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 method looks for the first result that matches the expression passed as argument. When it doesn't find any, it will throw this exception. If you are not sure that the sequence contains the element you are looking for, use FirstOrDefault. See this 文章进行了很好的总结。