我正在将C#8,.net标准2.0与MongoDB.Driver v2.9.2一起使用。我正在将一个项目从RavenDB迁移到MongoDB。
我需要在我的GetAllAsync方法中对IMongoQueryable使用 include ,但我感到困惑。这是方法;
public async Task<ICollection<TEntity>> GetAllAsync<TOrderBy>(Expression<Func<TEntity, TOrderBy>> orderBy,
bool isDescendingOrder = false,
Expression<Func<TEntity, object>> projection = null,
CancellationToken cancellationToken = default)
{
IMongoQueryable<TEntity> mongoQueryable = Collection.AsQueryable();
if (isDescendingOrder)
{
return await mongoQueryable.OrderByDescending(orderBy)
.ToListAsync(cancellationToken: cancellationToken);
}
return await mongoQueryable.OrderBy(orderBy)
.ToListAsync(cancellationToken: cancellationToken);
}
到目前为止我尝试过的我可以使用“ Find()”方法构建相同的查询,但是
SortByDescending方法需要“ Expression<Func<TEntity, object>> orderBy
”-不能与Expression<Func<TEntity, TOrderBy>> orderBy
一起使用,就像我提供的上层代码块一样。
Builders<TEntity>.Sort.Ascending(orderBy).
Func<TEntity, TOrderBy> compile = orderBy.Compile();
Collection.Find(new BsonDocument()).Project(projection).SortByDescending(compile).ToListAsync();
最后一件事,这就是我如何在RavenDB中解决此问题:
public async Task<ICollection<TEntity>> GetAllAsync<TOrderBy>(Expression<Func<TEntity, TOrderBy>> orderBy,
bool isDescendingOrder = false,
Expression<Func<TEntity, object>> projection = null,
CancellationToken cancellationToken = default)
{
ICollection<TEntity> entities;
IRavenQueryable<TEntity> query = AsyncDocumentSession.Query<TEntity>();
if (projection != null)
{
query = query.Include(projection);
}
if (isDescendingOrder)
{
entities = await query.OrderByDescending(orderBy)
.ToListAsync(token: cancellationToken);
}
else
{
entities = await query.OrderBy(orderBy)
.ToListAsync(token: cancellationToken);
}
return entities;
}
答案 0 :(得分:1)
尝试以下操作:
BindingSources
测试程序:
ComboBoxes