I'm working on integrating MongoDB / LINQ with my codebase, and I keep reading about these FirstOrDefaultAsync
or ToListAsync()
methods from the MongoDB Driver. However, I don't have those available. Am I missing some NuGet packages that everyone else uses? I'm using .NET 7.0.
using Mangler.Common.Functions;
using ManglerAPI.Infrastructure.Mongo;
using ManglerAPI.Stories.Entities;
using MongoDB.Driver.Linq;
using MongoDB.Driver;
namespace ManglerAPI.Stories.Repositories;
public interface IStoryRepository
{
Task<OperationResult<Story>> GetById(long id);
}
public class StoryMongoRepository : IStoryRepository
{
private readonly IQueryable<Story> _stories;
public StoryMongoRepository(MongoClientFactory clientFactory)
{
_stories = clientFactory.GetClient<Story>("Stories");
}
public async Task<OperationResult<Story>> GetById(long id)
{
// FirstOrDefault does not exist.
var data = await _stories.FirstOrDefaultAsync();
return data is null ?
OperationResult<Story>.Failure(ResultCode.EntityNotFound) :
OperationResult<Story>.Success(data);
}
}
The problem was the IQueryable<T>
is from the System.Linq which doesn't have the FirstOrDefaultAsync
and ToListAsync
extension method.
Instead, you should use the IMongoQueryable<T>
from MongoDB.Driver.Linq.
private readonly IMongoQueryable<Story> _stories;
And you need to modify
using MongoDB.Driver.Linq;
public class MongoClientFactory
{
public IMongoQueryable<T> GetClient<T>(string collectionName)
{
MongoClient client = /* Mongo Client instance */
IMongoDatabase db = client.GetDatabase(/* Your database */);
return db.GetCollection<T>(collectionName).AsQueryable();
}
}