I’m working on integrating MongoDB with ASP.NET Core using Entity Framework patterns. Currently, EF Core 8.0.11 provides a clean DI setup for relational databases like this:
builder.Services.AddDbContext(opt => { opt.UseNpgsql(connectionString); });
I attempted to use a similar approach with MongoDB:
builder.Services.AddDbContext(opt => { opt.UseMongoDB(“mongodb://localhost:27017”, “mydatabase”); });
However, when I try to execute a query, I get the following error:
System.ArgumentException: The source argument must be a MongoDB IQueryable. (Parameter ‘source’)
The error occurs in this code:
using var scope = _scopeFactory.CreateScope(); var context = scope.ServiceProvider.GetRequiredService();
// Line below causes the error
MongoProductContext pressureOptionsCollection = context.PressureOptions.AsQueryable(); var pressureOptions = await MongoDB.Driver.Linq.MongoQueryable.FirstOrDefaultAsync( pressureOptionsCollection, po => po.Type == type );
Environment:
- .NET 8
- EntityFrameworkCore 8.0.11
- MongoDB.EntityFrameworkCore 8.2.1
- ASP.NET Core Web API project
Thanks!