2

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?

trallallalloo
  • 592
  • 1
  • 9
  • 25
  • What is the message of exception? – Sohaty May 08 '15 at 07:05
  • it says "sequence contains no elements". but i debugged that db connection have done successfully and there is a collection which is "city". – trallallalloo May 08 '15 at 07:17
  • @vedat That means that `collection` does not have an element being equal to "VIENNA". Use `FirstOrDefault` instead. – molnarm May 08 '15 at 07:25
  • @MártonMolnár thanks for answer. I thought that first documents' city field is "VIENNA" but I understand that functionality of First function is different. So I'm querying with _id. – trallallalloo May 08 '15 at 07:38

1 Answers1

2

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.

molnarm
  • 9,856
  • 2
  • 42
  • 60