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 package that everyone else uses? I’m on .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);
}
}
2
Answers
The problem was the
IQueryable<T>
is from the System.Linq which doesn’t have theFirstOrDefaultAsync
andToListAsync
extension method.Instead, you should use the
IMongoQueryable<T>
from MongoDB.Driver.Linq.And you need to modify
These async methods are extensions for
IMongoQueryable
, notIQueryable
(which is a base interface forIMongoQueryable
). So you should work with the interface that is provided for you byAsQueryable
method, ie withIMongoQueryable