c# - MongoDB Linq 驱动程序转换异常

标签 c# linq mongodb

我正在尝试连接到 MongoDB 并使用 linq 搜索集合。我使用 Nuget 安装了所有的 mongo 工具,并收到一条错误消息,指出 GetCollection 返回 IMongoCollection,但 AsQueryable 需要一个 MongoCollection。我知道我可以在这里解决问题,我想我可能做错了什么。这是我的代码:

using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MongoDB.Bson;

namespace Services.Data.Repositories.Concrete
{


    public class AccountRepository : IRepository<Account>
    {
        private IMongoDatabase _database;
        private IMongoClient _client;

        public AccountRepository()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
            _client = new MongoClient(connectionString);
           _database = _client.GetDatabase("test");

        }
        public async Task<Account> GetAsync(string id)
        {
            var accounts = _database.GetCollection<Account>("accounts");
            var account = await accounts.Find(f => f.Id == id).FirstAsync();
            return account;
        }

        public async Task<List<Account>> GetAllAsync(bool onlyActive)
        {
            var accounts = _database.GetCollection<Account>("accounts");
            return accounts.AsQueryable<Account>().ToList();
        }

如果您查看 GetAllAsync 方法,就会发现这是我遇到编译错误的地方。我在这里做错了什么吗?

异常: 错误 5 Instance argument: cannot convert from 'MongoDB.Driver.IMongoCollection' to 'MongoDB.Driver.MongoCollection'

更新 我检查了 IMongoCollection 接口(interface)上没有 FindAll 方法。我可以用下面的代码暂时解决我的问题,但它看起来肯定不是最好的方法。有没有我遗漏的东西或者这个标准实现?

    public async Task<List<Account>> GetAllAsync(bool onlyActive)
    {
        var accounts = _database.GetCollection<Account>("accounts") as MongoCollection;
        return accounts.AsQueryable<Account>().ToList();
    }

最佳答案

可以看到AsQueryable的定义:

public static IQueryable<T> AsQueryable<T>(this MongoCollection<T> collection);
public static IQueryable<T> AsQueryable<T>(this MongoCollection collection);.

参数是 MongoCollection ...

你可以改变

return accounts.AsQueryable<Account>().ToList();

return accounts.FindAll();

关于c# - MongoDB Linq 驱动程序转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335930/

相关文章:

c# - Visual Studio 2010 Pro,在应用程序关闭时不结束 Debug模式

vb.net - linq中的后期绑定(bind)

linq - 按大于 0 的排序顺序排序

swift - 如何将vapor连接到mongodb atlas

C# : Check value stored inside string object is decimal or not

c# - 在.net中创建圆形头像

c# - 使用 LINQ GroupBy 获取忽略属性的唯一集合

mongodb - 如何在 node.js 中将数据转换为 utf-8?

java - 无法 Autowiring MongoOperations bean

c# - 一定数量的API调用后Azure服务器抛出异常