我知道var只在其范围内。但是,我遇到了收集品种的情况。从数据库连接方法,需要在后续的Query()方法中进行访问才能进行查询。
具体错误是:The name collection doesn't exist in the current context
我已经引用MongoDB C# driver docs来设置连接和查询,除了这个问题外,所有内容似乎都是正确的。
有谁知道如何重构我的代码以解决错误?
我的两个方法在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();
}
这是客户模型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; }
}
答案 0 :(得分:3)
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
创建的集合一起使用是有意义的,并且您不会将创建的对象用于其他任何事情,那么您可以{{1}直接调用FindCustomer
,但赔率不适用。