Search code examples
c#linqmongodbasqueryable

getting InvalidOperationException while querying with AsQueryable in C#


I have an entity class as 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; }

and I want to create a simple query with AsQueryable() class. Here is my query code

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());
}

When I run the code I get an System.InvalidOperationException like this

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

at

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

line. Can anyone explain that why I'm getting this exception and lead to solution?


Solution

  • The 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 article for a nice summary.