我将 Mongodb 驱动程序升级到最新的 2.0,我的应用程序过去工作失败并出现以下错误:
cannot convert from 'MongoDB.Driver.IMongoCollection<>' to 'System.Collections.Generic.IEnumerable<>'
源码如下:
public IQueryable<Registration> Registrations
{
get
{
return db
.GetCollection<Registration>("Registrations")
.AsQueryable<Registration>();
}
}
知道如何解决这个问题吗?
最佳答案
在新的 MongoDB Driver 中,整个事情现在都基于异步方法,所以旧的查询数据的方法不再适用。
基本上,您需要创建一个带有查找方法的 MongoRepository 类,并且该存储库可以具有以下查找方法:
public class MongoRepository<T>
{
protected IMongoCollection<T> _collection;
public MongoRepository(string collectionName)
{
// Get your mongo client and database objects here.
_collection = _mongoDb.GetCollection<T>(collectionName);
}
public async Task<IList<T>> Find(Expression<Func<T, bool>> query)
{
// Return the enumerable of the collection
return await _collection.Find<T>(query).ToListAsync();
}
}
然后可以这样实现:
MongoRepository<Registration> repo = new MongoRepository("Registrations");
IList<Registration> registrations = repo.Find(i => i.SomeProperty == true);
这里有一些关于如何实现 API 更改的有用信息:http://mongodb.github.io/mongo-csharp-driver/2.0/upgrading/
关于c# - 无法从 'MongoDB.Driver.IMongoCollection<>' 转换为 'System.Collections.Generic.IEnumerable<>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158700/