首页 > 其他分享 >OData – Get Started 搭建单侧环境

OData – Get Started 搭建单侧环境

时间:2023-03-19 16:33:31浏览次数:53  
标签:Get Started OData db Microsoft modelBuilder using AspNetCore

前言

之前写过 EF Core – Get Started 搭建单侧环境, 这篇补上一个 WebApi + EF Core + OData

 

创建项目

dotnet new webapi -o EfCoreODataWebApi

是 new webapi 哦, 不是 webapp

 

Install NuGet

dotnet add package Microsoft.AspNetCore.OData

EF Core 的我就不写了

 

Files

ProductController.cs

using System.Net.Mime;
using EfCoreODataWebApi.Entity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Attributes;

namespace EfCoreODataWebApi.Controllers;

[ApiController]
[Route("api")]
public class ProductController : ControllerBase
{
    private readonly ApplicationDbContext _db;

    public ProductController(
        ApplicationDbContext db
    )
    {
        _db = db;
    }

    [ODataAttributeRouting]
    [EnableQuery]
    [HttpGet("products")]
    [Produces(MediaTypeNames.Application.Json)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult<IEnumerable<Product>> GetProducts()
    {
        return Ok(_db.Products);
    }
}

Program.cs

var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Product>("products");

builder.Services.AddControllers().AddOData(
    options => options.Select().Filter().OrderBy().Expand().Count().SetMaxTop(null).AddRouteComponents(
        "api",
        modelBuilder.GetEdmModel()
    )
);

它只需要添加 Services 就可以了.

 

访问 API

https://192.168.1.152:44300/api/products?$filter=Id%20ge%203

 

  

标签:Get,Started,OData,db,Microsoft,modelBuilder,using,AspNetCore
From: https://www.cnblogs.com/keatkeat/p/17233495.html

相关文章