I am trying to connect to MongoDB and search the collection using linq. I used Nuget to install all the mongo tools, and I get a message that GetCollection returns IMongoCollection, but AsQueryable requires MongoCollection. I know that I can quit here to solve the problem, I think that I'm probably doing something wrong. Here is my code:
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();
}
If you look at the GetAllAsync method, I get a compilation error. Is something I am doing wrong here?
Exception: Error 5 Argument instance: cannot convert from "MongoDB.Driver.IMongoCollection" to "MongoDB.Driver.MongoCollection"
FindAll IMongoCollection. , , , . -, ?
public async Task<List<Account>> GetAllAsync(bool onlyActive)
{
var accounts = _database.GetCollection<Account>("accounts") as MongoCollection;
return accounts.AsQueryable<Account>().ToList();
}