我正在创建一个单例类来查询 .Net 6 Web api 中的 mongo 集合。由于我的应用程序将查询 3 个不同数据库中的多个不同集合,因此我正在创建一个函数来接收集合和数据库的名称以及查询参数。
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;
}
}
当前类只有一个以 FilterDefinition 作为参数的函数,但我也希望有一个类似的函数,允许我使用 Linq 作为参数。我怎样才能做到这一点?
这就是我希望调用该函数的方式:
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 );
这就是我正在尝试做的,目前不起作用,因为Where()不接受FindOptions并且没有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();
}
不确定我理解这个问题,但如果你问为什么
Where
不接受FindOption
,那么这是因为Where
在幕后使用Aggregate
,而不是查找。这就是为什么您必须指定 AggregateOptions
(允许类似的选项)。你必须将它们传递到 AsQueryable
方法