Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement Minimal Controller

I have an ASP.NET Core 1.1 Web Project.

I have installed Microsoft.OData.Core and followed linked "Getting Started" under http://odata.github.io/.

Both the following Links on that page are for .Net 45

  • “Build an OData v4 Service with RESTier Library”
  • “Build an OData v4 Service with OData WebApi Library”

This month old SO answer links to Microsoft.AspNetCore.OData which is NOT owned by Microsoft and was last updated over a year ago.

This SO answer implies "OData Support in ASP.net core"

I see this third party solution AutoODataEF.Core to auto generate controllers however.

Lastly, I see this git issue indicates OData WebAPI for ASP.Net Core is forth coming, but ultimately not currently available.

Assuming I have a Person Model and an EF DbContext.

How do I implement a minimal OData Controller?

like image 411
ttugates Avatar asked Sep 15 '17 14:09

ttugates


1 Answers

odata on asp.net core netcoreapp2.0, 20180216

  1. install-package Microsoft.AspNetCore.OData -Pre {7.0.0-beta1}

  2. in Startup.cs:

    public virtual void ConfigureServices(IServiceCollection services)
    {
        // ...
        services.AddMvc(); // mvc first
        services.AddOData(); // odata second
    }
    
    public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // ...
        var builder = new ODataConventionModelBuilder(serviceProvider);
        builder.EntitySet<SomeClass>(nameof(SomeClass).ToLower()).EntityType.HasKey(s => s.SomeId);        
        builder.EntitySet<OtherClass>(nameof(OtherClass).ToLower()).EntityType.HasKey(s => s.OtherId).MediaType();   // etc
        var model = builder.GetEdmModel();
    
        app.UseMvc(routeBuilder =>
        {            
            routeBuilder.Select().Expand().Filter().OrderBy().MaxTop(null).Count();
            routeBuilder.MapODataServiceRoute("ODataRoute", "data", model); // e.g. http://localhost:port/data/someclass?...
            // insert special bits for e.g. custom MLE here
            routeBuilder.EnableDependencyInjection();
            routeBuilder.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); // enable mvc controllers
        });    
    }
    
  3. in SomeClassController.cs:

    public class SomeClassController : ODataController // or just plain Controller
    {
        [EnableQuery]
        [HttpGet]
        [ODataRoute("someclass")]
        public List<SomeClass> Get() // this should maybe be an IQueryable wrapped by an IActionResult/OkObjectResult
        {
            List<SomeClass> list = new List<SomeClass>();
            // however you do this
            return list;
        }
    }
    
like image 200
user326608 Avatar answered Sep 28 '22 06:09

user326608