簡體   English   中英

如何從另一方法的一種方法引用“ var”?

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

我知道var僅在其方法范圍內。 但是我遇到過這樣一種情況,需要在隨后的Query()方法中訪問數據庫連接方法中的集合“ var”以進行查詢。

特定的錯誤是: The name collection doesn't exist in the current context

我一直在參考MongoDB C#驅動程序文檔以設置連接和查詢,除了此問題外,其他所有方法似乎都是正確的。

有誰知道我如何重組我的代碼來解決錯誤?

我的兩個方法在OrderRespository類中指定如下,該類建立數據庫連接和查詢:

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

    }

這是對收集字段進行建模的客戶Model POCO類:

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

    }

CreateConnection應該返回它正在創建的集合,以便創建連接的人可以實際使用它:

//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可以接受該集合作為參數:

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

然后,您可以使用CreateConnection創建您要搜索的文檔:

var customers = FindCustomers(CreateConnection());

如果FindCustomers是只能與CreateConnection創建的集合一起使用的東西,而您絕不會將創建的對象用於其他任何東西,則可以讓FindCustomer直接調用CreateConnection ,但是很可能這些條件將不適用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM