c# - 无法从 'MongoDB.Driver.IMongoCollection<>' 转换为 'System.Collections.Generic.IEnumerable<>'

标签 c# mongodb

我将 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/

相关文章:

c# - WPF 按钮按下/释放绑定(bind)

c# MVC 5 RouteConfig 重定向

node.js - 从nodejs在mongodb中插入一大堆对象

node.js - Nodejs、Mongodb 关注/取消关注请求

c# - SQLite :memory: database usage with using/dispose

c# - C#中如何将DataTable转换为对象类型List

c# - 从 Tap (TapGestureRecognizer) 事件中提取 byte[] 到 Xamarin Forms 中的 Click 事件

mongodb - 使用文档中存储的值查询 $near

jquery - Mongoose 插入\u0000

c# - MongoDB.net 驱动程序 - 项目到不同的类