【发布时间】:2014-02-01 20:44:29
【问题描述】:
我正在尝试抽象 VS 2013 中自动生成的 ODataController 类,因为除了 POCO 的名称之外,不同控制器的代码看起来相同,因此,我执行了以下操作:
public abstract class ODataControllerBase<T,DB> : ODataController
where T : class, IIdentifiable, new()
where DB : DbContext, new()
{
protected DB _DataContext;
public ODataControllerBase() : base()
{
_DataContext = new DB();
}
// only one function shown for brevity
[Queryable]
public SingleResult<T> GetEntity([FromODataUri] int key)
{
return SingleResult.Create(_DataContext.Set<T>().Where(Entity => Entity.Id.Equals(key)));
}
}
IIdentifiable 是一个接口,它强制 T 参数具有可读/可写的 Id 整数属性。
实现看起来像这样(POCO 和 DataContexts 应该已经创建好了)
public class MyObjectsController : ODataControllerBase<MyObject,MyDbContext>
{
public MyObjectsController() : base()
{
}
// That's it - done because all the repetitive code has been abstracted.
}
现在,我的 WebApiConfig 的注册函数只包含以下内容:
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<MyObject>("MyObjects");
config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
}
我运行该项目,http://localhost:10000/odata/MyObjects 并得到响应:
<m:error>
<m:code/>
<m:message xml:lang="en-US">No HTTP resource was found that
matches the request URI `http://localhost:10000/odata/MyObjects.`
</m:message>
<m:innererror>
<m:message>No routing convention was found to select an action
for the OData path with template '~/entityset'.
</m:message>
<m:type/>
<m:stacktrace/>
</m:innererror>
</m:error>
缺少什么?我应该删除什么?这是我们不能做的事情吗,即我们真的需要直接继承ODataController而不需要中间父类吗?
【问题讨论】:
-
你有返回所有对象的动作吗?例如
Get()这样的动作? -
是的。示例函数是一个返回一个对象的 Get 函数...除非 Get 操作也必须命名为 GetMyObject,因为操作名称是路由敏感的?如果是这样,那么这就是其中的秘密之一。
-
问题已修复:将操作 GetEntity([FromODataUri]int key) 更改为普通 Get([FromODataUri]int key)。抽象控制器时,不要在 CRUD 操作上附加任何内容。
-
@MickaelCaruso - 你想自己发布答案,这个问题从外面看起来没有答案
-
我遇到了同样的问题,但我的问题是由于在 BaseController 中的 Get 方法上使用 protected 而不是 public 引起的。基本方法必须是公开的。
标签: asp.net asp.net-web-api odata