我有很多不同的实体想要启用 OData。这些实体根据其类型分为不同的组。目前,默认是将 EntitySet 与 Controller 名称相匹配,但我不希望我拥有的每个实体类型都有一个 Controller 。有没有一种方法可以将多个 EntitySet 映射到一个 Controller 。
我试过让我感兴趣的类型实现一个公共(public)接口(interface),并将该接口(interface)指定为我的实体集类型。我还尝试过在一个 Controller 中有两个实体并使用它们自己的 get 请求,但没有成功。我还尝试定义自己的路由类来扩展 EntitySetRoutingConvention,但还没有成功。
网络接口(interface)配置
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<MyEntity1>("MyEntity1");
builder.EntitySet<MyEntity2>("MyEntity2");
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
// Web API routes
config.MapHttpAttributeRoutes();
}
这将查找名为 MyEntity1Controller 和 MyEntity2Controller 的 Controller 。 我想要的是这样的:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<MyEntity1>("Generic");
builder.EntitySet<MyEntity2>("Generic"); // Throws an error since Generic is already registered to MyEntity1
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
// Web API routes
config.MapHttpAttributeRoutes();
}
通用 Controller .cs
// GET: odata/myentity1
[EnableQuery]
public IQueryable<MyEntity1> GetMyEntity1()
{
return db.MyEntity1.AsQueryable();
}
// GET: odata/myentity2
[EnableQuery]
public IQueryable<myentity2> GetMyEntity2()
{
return db.MyEntity2.AsQueryable();
}
预期的结果是我可以转到 myurl/Generic/MyEntity1,这会在我的通用 Controller 中触发 GET 请求。我还应该能够执行 odata 操作,例如 myurl/Generic/MyEntity1?$select=Id。
最佳答案
添加 ODataRoute 属性
/// MyController.cs
// GET: odata/myentity1
[EnableQuery]
[ODataRoute("myentity1")]
public IQueryable<MyEntity1> GetMyEntity1() => db.MyEntity1.AsQueryable();
// GET: odata/myentity2
[EnableQuery]
[ODataRoute("myentity1")]
public IQueryable<MyEntity2> GetMyEntity2() => db.MyEntity2.AsQueryable();
关于c# - 如何将多个实体集绑定(bind)到一个 odata Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57616954/