【问题标题】:Updating Navigation Property in oData WebAPI在 oData WebAPI 中更新导航属性
【发布时间】:2013-06-27 00:13:34
【问题描述】:

我正在使用 WebAPI oData。要求是更新实体的 Navigation 属性。

public class Question
{
    public int QuestionId { get; set; }
    public string QuestionTitle { get; set; }
    public string QuestionBody { get; set; }
    public List<Response> Responses { get; set; } //navigation property
}

public class Response
{
    public string ResponseId { get; set; }
    public int QuestionId { get; set; } //fk
    public string ResponseBody { get; set; }
}

现在,如果我使用以下链接来获取它在 oData Webapi 中的响应

GET - /odata/questions(1)/responses ----成功。 在控制器中,我添加了一个操作来处​​理这个请求:

public IQueryable<Response> GetResponses([FromODataUri] Guid key)
{
    //
}

POST - /odata/questions(1)/responses ----这不起作用;错误 消息是:此服务不支持“~/entityset/key/navigation”形式的 OData 请求

我在控制器中添加的方法是:

public List<Responses> CreateResponses([FromODataUri] Guid key, List<Response> responses)
{
     //
}

如何支持在 oData WebAPI 中添加/更新导航属性

【问题讨论】:

    标签: odata asp.net-web-api-routing


    【解决方案1】:

    您需要一个自定义路由约定来处理 POST 到导航属性。代码如下,

    // routing convention to handle POST requests to navigation properties.
    public class CreateNavigationPropertyRoutingConvention : EntitySetRoutingConvention
    {
        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
        {
            if (odataPath.PathTemplate == "~/entityset/key/navigation" && controllerContext.Request.Method == HttpMethod.Post)
            {
                IEdmNavigationProperty navigationProperty = (odataPath.Segments[2] as NavigationPathSegment).NavigationProperty;
                controllerContext.RouteData.Values["key"] = (odataPath.Segments[1] as KeyValuePathSegment).Value; // set the key for model binding.
                return "PostTo" + navigationProperty.Name;
            }
    
            return null;
        }
    }
    

    注册路由约定,

    var routingConventions = ODataRoutingConventions.CreateDefault();
    routingConventions.Insert(0, new CreateNavigationPropertyRoutingConvention());
    server.Configuration.Routes.MapODataRoute("odata", "", GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
    

    完整的示例是here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多