12

OData is now supported in .NET Core and 7.2.0 was released. But can it be used with MongoDB? I have searched, but I could not find anything that says one way or the other.

EDIT:

I've found a nuget package https://www.nuget.org/packages/microsoft.aspnetcore.odata and in ConfigureServices I've 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();
}

Repositories

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 it?

I mean, shouldn't the collection contain only the elements that meet the filters, beeing more optimised?

If yes, how do I achieve this?

Gerald Hughes
  • 5,771
  • 20
  • 73
  • 131
  • 1
    Technically, nothing prevents you from querying MongoDB and returning OData if both can run in the same process (note OData by itself is not tied to Entity Framework at all), so the answer is "yes". But the difficulty is how do you go from a NoSQL/Schema-Less document to tabular data (OData is tabular data-oriented, it was developped for Excel)? There cannot be a generic solution to this problem. See a similar and recent discussion on CosmosDB: https://stackoverflow.com/questions/54499430/odata-and-cosmos-db#comment95903186_54499430 If you have a more precise question, we can work on it. – Simon Mourier Feb 23 '19 at 17:37
  • 1
    Why do you convert collection to array? ToArray will run the query on database, enumerate the result to get the array. That's the only source of inefficiency in your code (https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.toarray?view=netcore-2.2). Repository variable "collection" is already IQueryable; just return that. – zendu Mar 02 '19 at 04:49
  • `collection.ToArray()` is just wrong – hyankov Mar 13 '19 at 19:04

2 Answers2

3

I think theres only currently one connected service available in the visual studio market place for MongoDB. Link Here.

ODBC Driver for MongoDB provides high-performance and feature-rich connectivity solution for ODBC-based applications to access MongoDB databases from Windows, MacOS, Linux. Full support for standard ODBC API functions, MongoDB data types and SQL queries implemented in our driver makes interaction of your database applications with MongoDB fast, easy and extremely handy.

Looks like it would handle all of the things you'd expect it to when connecting to MongoDB.

However it's worth noting that, that is only a trail and I've been unable to find any 'open source' versions

JoeTomks
  • 3,243
  • 1
  • 18
  • 42
  • 1
    It is worth noting that there are other options on the Visual Studio Marketplace. (Full disclosure, CData Software is my employer). The ADO.NET Provider by CData Software provides a native experience in .NET: https://marketplace.visualstudio.com/items?itemName=CDATASOFTWARE.MongoDBADONETProvider. If you're looking to create an OData interface for MongoDB, the [API Server](http://www.cdata.com/apiserver) by CData Software does just that. Like the above, these are paid solutions. – Jerod Johnson Jul 20 '17 at 18:27
  • 1
    This answer isn't clear to me. For custom app development in a .NET MVC + SQL Server environment we'd simply use nuget package Microsoft.AspNet.OData. In a .NET Core + MongoDB environment is the recommendation (and only available solution) to use a MongoDB ODBC driver + nuget package Microsoft.AspNetCore.OData (currently in alpha)? – Matthew Dec 19 '17 at 16:54
  • @Aydus-Matthew bear in mind that this was answered in July. Because of the nature of the question t's likely that my answer could become out of date. In this instance the shift to VS 2017 and the OData packages available for example. I believe what you're talking about came about after my answer was posted. At some point I'll likely update the above answer with an up to date response. – JoeTomks Jan 02 '18 at 13:18
  • I'm sorry but I'm confused. Why do you need ODBC driver to create an OData service? – gyozo kudor Jan 12 '18 at 12:32
  • 1
    @gyozokudor at the time I posted my answer the only bi-directional data driver that worked with MongoDB from the OPs solution would have been the OBDC driver, that obviously is no longer the case. When I get chance I'll update my answer to reflect the current best practice for achieving what the OP asked. – JoeTomks Jan 12 '18 at 14:09
0

MongoDB OData Connector http://cdn.cdata.com/help/DGB/cd/ Its not free https://www.cdata.com/drivers/mongodb/download/ Overview

The MongoDB OData Connector application enables you to securely access data from MongoDB in popular formats like OData, JSONP, SOAP, RSS, and more. The Getting Started section explains how to establish the connection to MongoDB. In this section, you will find a guide to setting required connection properties and allowing the OData connector to access MongoDB tables. The Supported OData section shows the OData syntax supported by the OData connector and points out any limitations when querying live data. The OData connector can be installed as a stand-alone application or integrated with your server. In the Server Configuration section you will find information on how to install the OData connector on an existing server configuration. System requirements are also listed here. You will also find instructions on how to manage users and deploy SSL. Logging details the available logging resources. The OData API enables access to your data from any application with Web connectivity. The OData connector supports all major authentication schemes. This section documents HTTP methods supported by the server, server responses, and supported authentication schemes. The Data Model section lists the tables, views, and stored procedures available for the application.

Jin Thakur
  • 2,711
  • 18
  • 15