I’m creating a singleton class to query mongo collections in a .Net 6 web api. Since my application will query several different collections in 3 different databases so I’m making a function that receives the names of the collection and database together with the query parameters.
public class MongoReader
{
private MongoClient _client;
public MongoReader(string connectionString)
{
ConventionPack pack = new ConventionPack();
pack.Add(new IgnoreExtraElementsConvention(true));
ConventionRegistry.Register("My Solution Conventions", pack, t => true);
_client = new MongoClient(connectionString);
}
public async Task<List<T>> QueryCollection<T>(string collection, FilterDefinition<T> filter,int limit = 50,int batchSize = 50) where T : class
{
string[] collectionInformation = collection.Split('.');
string collectionName = collectionInformation[1];
string collectionDatabase = collectionInformation[0];
List<T> list = new List<T> ();
FindOptions<T> findOptions = new FindOptions<T>() { Limit = limit , BatchSize = batchSize };
IAsyncCursor<T> cursor = await _client.GetDatabase(collectionDatabase).GetCollection<T>(collectionName).FindAsync(filter, findOptions);
list = await cursor.ToListAsync();
return list;
}
}
The current class only has a function with FilterDefinition as parameter but I also wish for a similar function that would allow me to use Linq as an argument. How can i do that?
This is how I wish to call the function :
MongoReader _reader = new MongoReader("connectionstring");
int limit = 50;
int batchSize = 50;
List<RandomClass> list = await _reader.QueryCollectionLinqAsync<RandomClass>("DatabaseName.CollectionName", t => t.fieldName == fieldValue,limit ,batchSize );
This is what I’m trying to do , currently not working because Where() doesn’t accept FindOptions and doesn’t have ToListAsync() :
public async Task<List<T>> QueryCollection<T>(string collection, Func<T,bool> predicate, int limit = 50, int batchSize = 50) where T : class
{
string[] collectionInformation = collection.Split('.');
string collectionName = collectionInformation[1];
string collectionDatabase = collectionInformation[0];
List<T> list = new List<T>();
FindOptions<T> findOptions = new FindOptions<T>() { Limit = limit, BatchSize = limit };
return await _client.GetDatabase(collectionDatabase).GetCollection<T>(collectionName).AsQueryable().Where(predicate,findOptions ).ToListAsync();
}