There are other questions like this one but non relating to the actual FindAsync from what I can tell.
My ClientsController calls ClientService.GetClients which uses the mongo drivers to query a mongodb on Azure.
Stepping through the debugger it gets up to the point where I call clientCollection.FindAsync. If I step over this the line following is never hit and no errors are given. It's like the awaited task never returns.
public async Task<List<Client>> GetClients(SearchRequestDTO searchRequest)
{
var response = new List<Client>();
var db = _databaseUtilityService.GetCoreDatabase();
var clientCollection = db.GetCollection<Client>(Properties.Settings.Default.ClientCollectionName);
var cursor = await clientCollection.FindAsync(new BsonDocument());
while (await cursor.MoveNextAsync())
{
response.Concat(cursor.Current.ToList());
}
return response;
}
What would be the reason why the debugger never steps over the var cursor = ... line ?
Edit-
I can instead get Result-
var cursor = clientCollection.FindAsync(new BsonDocument()).Result;
But I'm not sure that's what I want to do.
public async Task<List<Client>> GetClients(SearchRequestDTO searchRequest)
{
var db = _databaseUtilityService.GetCoreDatabase();
var clientCollection = db.GetCollection<Client>(Properties.Settings.Default.ClientCollectionName);
var results = clientCollection.FindAsync(new BsonDocument()).Result;
return results.ToList();
}
Since there is not much information about context, so I came up with mock classes to satisfy question.
Please see below an overloaded method and when called, it will always return you list of three records. Now what's wrong with your code? I believe it's in your while loop. You are calling response.Concat which is causing an issue.
I'm calling response.AddRange instead and it works.
public async Task<List<Client>> GetClients()
{
var mongoUri = "mongodb://localhost:27017";
var mongoClient = new MongoClient(mongoUri);
var mongoDatabase = mongoClient.GetDatabase("ClientDB");
var clientCollection = mongoDatabase.GetCollection<Client>("Clients");
// Empty collection to always get accurate result.
clientCollection.DeleteMany(new BsonDocument());
// Insert some dummy data
clientCollection.InsertOne(new Client() {Address = "One street, some state", ZipCode = 11111});
clientCollection.InsertOne(new Client() { Address = "2nd street, some state", ZipCode = 22222 });
clientCollection.InsertOne(new Client() { Address = "Third street, some state", ZipCode = 33333 });
var response = new List<Client>();
var cursor = await clientCollection.FindAsync(new BsonDocument());
while (await cursor.MoveNextAsync())
{
response.AddRange(cursor.Current);
}
return response;
}