【发布时间】:2021-10-22 11:45:32
【问题描述】:
我有一个函数,我用它从 Mongo DB 中通过 ID 检索对象,它看起来像这样:
public async Task<IEnumerable<TItem>> GetItemsAsync(uint limit,
Expression<Func<TItem, bool>> filter = null,
SortDefinition<TItem> sort = null,
ProjectionDefinition<TItem> projection = default,
CancellationToken token = default) {
// First, create the options describing which objects will be returned
var findOptions = new FindOptions<TItem> {
Limit = (int)limit,
Sort = sort,
Projection = projection
};
// Next, connect to the specific collection in the database
IMongoCollection<TItem> collection = GetCollection();
// Now, attempt to find all the items associated with the filter and find options
IAsyncCursor<TItem> cursor = await collection.FindAsync(filter ?? FilterDefinition<TItem>.Empty,
findOptions, token).ConfigureAwait(false);
// Finally, retrieve all the items and return them
return await cursor.ToListAsync(token).ConfigureAwait(false);
}
我遇到的问题是,在我想从文档中返回所有字段并因此不提供投影的情况下,这会中断。在这种情况下,我得到以下异常:
System.ArgumentNullException: Value cannot be null. (Parameter 'projection')
at MongoDB.Driver.Core.Misc.Ensure.IsNotNull[T](T value, String paramName)
at MongoDB.Driver.KnownResultTypeProjectionDefinitionAdapter`2..ctor(ProjectionDefinition`1 projection, IBsonSerializer`1 projectionSerializer)
at MongoDB.Driver.ProjectionDefinition`2.op_Implicit(ProjectionDefinition`1 projection)
我的问题是:是否有传递投影定义或以编程方式将从 MongoDB 文档检索到的所有字段映射到我的返回对象的方法?
【问题讨论】:
-
我会使用
Find(!=FindSync) 并使用流利的方法添加选项。
标签: c# mongodb projection