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?

4
  • What is the message of exception? Commented May 8, 2015 at 7:05
  • it says "sequence contains no elements". but i debugged that db connection have done successfully and there is a collection which is "city". Commented May 8, 2015 at 7:17
  • @vedat That means that collection does not have an element being equal to "VIENNA". Use FirstOrDefault instead. Commented May 8, 2015 at 7: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. Commented May 8, 2015 at 7:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.