Using OData in the .NET Core Web API for MongoDB

OData is now supported in .NET Core and 7.2.0. But can it be used with MongoDB? I searched, but I could not find anything that says anyway.

EDIT:

I found the nuget package https://www.nuget.org/packages/microsoft.aspnetcore.odata and in ConfigureServices I added this:

And this seems to work for me:

 public void ConfigureServices(IServiceCollection services) { ... services.AddOData(); services.AddSingleton<IODataModelManger, ODataModelManager>(DefineEdmModel); ... } private ODataModelManager DefineEdmModel(IServiceProvider services) { var modelManager = new ODataModelManager(); var builder = new ODataConventionModelBuilder(); builder.EntitySet<TestDTO>(nameof(TestDTO)); builder.EntityType<TestDTO>().HasKey(ai => ai.Id); // the call to HasKey is mandatory modelManager.AddModel(nameof(Something), builder.GetEdmModel()); return modelManager; } 

controller

 [HttpGet("all")] public async Task<IQueryable<TestDTO>> Get() { // plug your entities source (database or whatever) var test = await TestService.GetTest(); var modelManager = (IODataModelManger)HttpContext.RequestServices.GetService(typeof(IODataModelManger)); var model = modelManager.GetModel(nameof(Something)); var queryContext = new ODataQueryContext(model, typeof(TestDTO), null); var queryOptions = new ODataQueryOptions(queryContext, HttpContext.Request, Provider); return queryOptions .ApplyTo(test, new ODataQuerySettings { HandleNullPropagation = HandleNullPropagationOption.True }, null) .Cast<TestDTO>(); } 

Service

 public async Task<IQueryable<TestDTO>> GetTest() { return await GenericRepository.TestAll(); } 

Storage facilities

 public async Task<IQueryable<TEntity>> TestAll() { var res = new GetManyResult<TEntity>(); try { DateTime startTime = DateTime.Now; var collection = GetCollection<TEntity>().AsQueryable(); var entities = collection.ToArray<TEntity>().AsQueryable(); return entities } 

But is this the best way to do this?

I mean, shouldn't the collection only contain elements that match the filters are more optimized?

If so, how do I achieve this?

+5
source share
1 answer

I think that at the moment only one connected service is available in the visual studio market for MongoDB. Link here.

The ODBC driver for MongoDB provides a high-performance and multi-functional solution for connecting ODBC applications to access MongoDB databases from Windows, MacOS, Linux. Full support for the standard ODBC API, MongoDB data types and SQL queries implemented in our driver interact with your MongoDB database applications quickly, easily and very conveniently.

It looks like it will handle everything you expect when connecting to MongoDB.

However, it is worth noting that this is only a trail, and I could not find the open source versions

+3
source

Source: https://habr.com/ru/post/1270016/


All Articles