我正在尝试连接到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实例参数:无法从'MongoDB.Driver.IMongoCollection'转换为'MongoDB.Driver.MongoCollection'
更新 我检查了IMongoCollection接口上没有FindAll方法。我能够使用下面的代码暂时解决我的问题,但它似乎不是最好的方法。我有什么遗漏或是这个标准的实施吗?
public async Task<List<Account>> GetAllAsync(bool onlyActive)
{
var accounts = _database.GetCollection<Account>("accounts") as MongoCollection;
return accounts.AsQueryable<Account>().ToList();
}
答案 0 :(得分:0)
你可以看到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();