Search code examples
c#mongodb-querymongodb-.net-driverpocovar

How to reference a 'var' from one method in another?


I know that a var is only in scope within it's method. But I've came across the situation where the collection 'var' from a database connection method, needs to be accessed in a subsequent Query() method in order to make a query.

The specific error is: The name collection doesn't exist in the current context

I've been referencing the MongoDB C# driver docs in order to set up the connection and the query and all seems correct besides this issue.

Does anyone know how I can restructure my code to resolve the error?

My two methods are specified as follows in an OrderRespository class, that makes database connections and queries:

//Method to create MongoDB Orders connection and get handle on collections
    public static bool CreateConnection()
    {

        var client = new MongoClient(connectionString);

        try
        {
          var database = client.GetDatabase("orders");
          //Get a handle on the customers collection:
          var collection = database.GetCollection<BsonDocument>("customers");
        }
        catch(MongoConnectionException)
        { 
            return false; 
        } 

        return true; 
    }



    //Method to test query on database documents
    public async static Task<List<Customer>> FindCustomers()
    {
        var documents =  await collection.Find(new BsonDocument()).ToListAsync();
        List<Customer> customerList = await documents.ToListAsync();

        return await documents.ToListAsync();

    }

And this is the customer Model POCO class that models the collection fields:

    public class Customer
    {
        /// <summary>
        /// This attribute is used to map the Id property to the ObjectId in the collection
        /// </summary>
        [BsonId]
        public ObjectId Id { get; set; }

        [BsonElement("firstName")]
        public string firstName { get; set; }

        [BsonElement("lastName")]
        public string lastName { get; set; }

        [BsonElement("email")]
        public string Email { get; set; }

    }

Solution

  • CreateConnection should return the collection that it's creating so that the person creating the connection can actually use it:

    //Consider renaming this method; you're really here to get the customers,
    //not create a connection
    public static YourCollectionType<BsonDocument> CreateConnection()
    {
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("orders");
        //Get a handle on the customers collection:
        return database.GetCollection<BsonDocument>("customers");
    }
    

    FindCustomers can then accept the collection as a parameter:

    public async static Task<List<Customer>> FindCustomers(
        YourCollectionType<BsonDocument> collection)
    {
        var documents =  await collection.Find(new BsonDocument()).ToListAsync();
        List<Customer> customerList = await documents.ToListAsync();
    
        return await documents.ToListAsync();
    }
    

    You can then use CreateConnection to create the documents that you search through:

    var customers = FindCustomers(CreateConnection());
    

    If FindCustomers is something that would only ever make sense to use with a collection created by CreateConnection and you won't ever use the created object for anything else, then you could have FindCustomer call CreateConnection directly, but odds are those conditions won't apply.