无法从“MongoDB.Driver.IMongoCollection<>"转换到“System.Collections.Generic.IEnumerable<>" [英] cannot convert from 'MongoDB.Driver.IMongoCollection<>' to 'System.Collections.Generic.IEnumerable<>'

查看:54
本文介绍了无法从“MongoDB.Driver.IMongoCollection<>"转换到“System.Collections.Generic.IEnumerable<>"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Mongodb 驱动程序升级到最新的 2.0,我的应用程序曾经运行失败并出现以下错误:

I upgraded Mongodb driver to the newest 2.0 and my application used to work failed with the error below:

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

cannot convert from 'MongoDB.Driver.IMongoCollection<>' to 'System.Collections.Generic.IEnumerable<>'

源代码如下:

public IQueryable<Registration> Registrations
{
    get 
    { 
        return db
            .GetCollection<Registration>("Registrations")
            .AsQueryable<Registration>(); 
    }
}

知道如何解决这个问题吗?

Any idea how to fix this?

推荐答案

在新的 MongoDB 驱动程序中,整个事物现在都基于异步方法,因此旧的查询数据方法不再适用.

In the new MongoDB Driver, the entire thing is now based on async methods, so the old methods for querying data no longer apply.

基本上,您会想要创建一个带有 find 方法的 MongoRepository 类,并且该存储库可以具有以下 Find 方法:

Basically, you would want to create an MongoRepository class, with a find method, and that repository could have the following Find method:

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/

There is some good information on how the changes to the API can be implemented here: http://mongodb.github.io/mongo-csharp-driver/2.0/upgrading/

这篇关于无法从“MongoDB.Driver.IMongoCollection&lt;&gt;"转换到“System.Collections.Generic.IEnumerable&lt;&gt;"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆