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
- Microsoft.AspNetCore.OData – 9.0.0
- 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();