我有一个ASP.NET(Core)应用程序,连接到SQL Server 2016实例。我需要发布一个通用的REST API,通过它可以查询数据库关系模式中的任何数据。我正在努力为此找到任何工具,它可以通过REST发布模式,或者至少从数据库模式生成API。
应用程序前端当然会使用特定的内部API:s,但这个通用接口将允许为外部应用程序发布整个模式。
答案 0 :(得分:4)
您可以在asp.net核心应用程序中将OData与EntityFramework核心一起使用,它仍然处于Beta 2状态,但我在生产应用程序中使用它并且运行良好(一些故障,但没有什么真正重要)。
您需要将以下NuGet引用添加到您的csproj文件中(如果您使用Visual Studio,只需使用NuGet包管理器):
<PackageReference Include="Microsoft.AspNetCore.OData" Version="7.0.0-beta2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" />
然后在您的启动文件中,按如下方式配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<YourEFDbContext>();
services.AddOData();
services.AddMvc(config => {
config.Filters.Add(new EnableQueryAttribute() {
PageSize = 100, //Default PageSize change to suit your needs
//This is used to speficy how many levels of related classes you can expand in your queries
MaxExpansionDepth = 3
});
});
}
您还需要提供一个Edm模型,其中包含您要公开的实体和功能:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//Expose OData entities
IEdmModel model = GetEdmModel(app.ApplicationServices);
// This is use to define the route for your service, in this case it will be http://localhost:5000/someservice
app.UseMvc(routeBuilder => routeBuilder.MapODataServiceRoute("odata", "someservice", model));
}
private static IEdmModel GetEdmModel(IServiceProvider serviceProvider)
{
var builder = new ODataConventionModelBuilder(serviceProvider);
//Expose the entity Client and allow to filter, orderby, page, expand and select
builder.EntitySet<Client>(nameof(Client)).EntityType.Count().Filter().OrderBy().Page().Expand(ExpandMaxDepth).Select();
builder.EntitySet<Address>(nameof(Address)).EntityType.Count().Filter().OrderBy().Page().Expand(ExpandMaxDepth).Select();
[...]
return builder.GetEdmModel();
}
最后,对于模型的每个实体,创建一个控制器,其中包含您要使用的REST操作:
public class ContactController
{
private YourDbContext _db;
public ContactController(YourDbContext db)
{
_db = db;
}
[EnableQuery()] //You don't actually need this because we added a filter in ConfigureServices
public IActionResult Get()
{
//Always return an IQueryable
return Ok(_db.Contacts.AsQueryable());
}
//Add PUT, PATCH and DELETE if needed...
}
运行您的服务,瞧!您已通过可在Windows,Linux和MacOS上运行的其他Web服务公开您的实体。
要试用它,您可以生成如下查询:
http://localhost:5000/Contact/?$ filter =姓名eq'John'
http://localhost:5000/Contact/ $顶部= 10&安培; $跳过= 10
http://localhost:5000/Contact/?$ expand = ContactAddress($ filter = AddressId eq 1234)
还有更多信息,请点击此处了解详情:http://www.odata.org/
修改强>
odata与创建自己的WebApi控制器有什么区别?与WebApi控制器相比的主要优点是odata支持可查询,例如,您可以在客户端中使用网格自动调用您的服务器并使用linq进行查询,就像它直接连接到数据库一样。以下是更多信息:
http://www.software-architects.com/devblog/2014/09/12/10-OData-FAQs https://www.progress.com/blogs/odata-faqs-why-should-rest-api-developers-use-odata