2 / 5
Nov 2024

I am using MongoDB.Driver with OData in a c# web api. My end point is working fine with $filter clause but when i use $select to retrieve a single property, my api crashes (screenshot attached).

NuGet Packages I am using

  1. Microsoft.AspNetCore.OData – 9.0.0
  2. MongoDB.Driver – 3.0.0

Controller

[ApiController]
[Route(“api/[controller]”)]
public class BooksController : ODataController
{
private readonly BooksService _booksService;

public BooksController(BooksService booksService) => _booksService = booksService; [HttpGet] [EnableQuery] public IQueryable<Book> Get() { return _booksService.GetAsync(); }

}

Books Service

public class BooksService
{
private readonly IMongoCollection _booksCollection;

public BooksService( IOptions<BookStoreDatabaseSettings> bookStoreDatabaseSettings) { var mongoClient = new MongoClient( bookStoreDatabaseSettings.Value.ConnectionString); var mongoDatabase = mongoClient.GetDatabase( bookStoreDatabaseSettings.Value.DatabaseName); _booksCollection = mongoDatabase.GetCollection<Book>( bookStoreDatabaseSettings.Value.BooksCollectionName); } public IQueryable<Book> GetAsync() { return _booksCollection.AsQueryable(); }

}

Program.cs

var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.Configure<BookStoreDatabaseSettings>( builder.Configuration.GetSection("BookStoreDatabase")); builder.Services.AddSingleton<BooksService>(); var modelBuilder = new ODataConventionModelBuilder(); var model = modelBuilder.EntitySet<Book>("Books").EntityType; model.HasKey(e => e.Id); builder.Services.AddControllers().AddOData(options => { options.Select().Filter().OrderBy().Expand().Count().SetMaxTop(100).AddRouteComponents("odata", modelBuilder.GetEdmModel()); }); var app = builder.Build(); app.UseHttpsRedirection(); app.UseRouting(); app.UseEndpoints(endpoints => endpoints.MapControllers()); //app.MapControllers(); app.Run();
14 days later

Hi Rishit,

I think there is a breaking change in MongoDriver 3.0.0 and as long as we migrate to this version we get this error:

"error": "Could not load type 'MongoDB.Driver.Linq.IMongoQueryable' from assembly 'MongoDB.Driver, Version=3.0.0.0, Culture=neutral, PublicKeyToken=94992a530f44e321'.",

As it seems that MongoDB.AspNetCore.OData is no longer copatible with v3.0 of the driver because IMongoQueryable is no longer available and now the approach would be to use IQueryable. Most likely the latest supported version for MongoDB.AspNetCore.OData is MongoDriver 2.30

9 days later

Hi @Bogdan_Grosu,

Welcome to the MongoDB Community Forums! You’re right, the current version of the MongoDB.AspeNetCore.OData package is not compatible with the v3.0 of the driver. The work is being tracked here. We’ll be aiming to address this in the coming weeks.

Thanks,

Rishit.

20 days later