skip to Main Content

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


  1. 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();
        }
    }
    
    Login or Signup to reply.
  2. These async methods are extensions for IMongoQueryable, not IQueryable (which is a base interface for IMongoQueryable). So you should work with the interface that is provided for you by AsQueryable method, ie with IMongoQueryable

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search