在oData WebAPI中更新导航属性 [英] Updating Navigation Property in oData WebAPI
问题描述
我正在使用WebAPI oData.要求是更新实体的Navigation属性.
I am using WebAPI oData. The requirement is to update the Navigation property of the entity.
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中的响应
Now if I use the following link to fetch the responses it works in oData Webapi
GET -/odata/questions(1)/response ----工作成功. 在控制器中,我添加了一个操作来处理此请求,如下所示:
GET - /odata/questions(1)/responses ----worked successfully. In the controller I added a action to handle this request as:
public IQueryable<Response> GetResponses([FromODataUri] Guid key)
{
//
}
POST -/odata/questions(1)/response ---- 这不起作用;错误 消息是:此服务不支持〜/entityset/key/navigation"形式的OData请求
POST - /odata/questions(1)/responses ----This is not working; error message is: This service doesn't support OData requests in the form '~/entityset/key/navigation'
我在控制器中添加的方法是:
The method I added in the controller is:
public List<Responses> CreateResponses([FromODataUri] Guid key, List<Response> responses)
{
//
}
我如何支持在oData WebAPI中添加/更新导航属性
How can I support adding/updating navigation properties in oData WebAPI
推荐答案
您需要使用自定义路由约定来处理POST的导航属性.下面的代码,
You need a custom routing convention to handle POST's to navigation properties. Code below,
// 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);
完整的示例是此处.
这篇关于在oData WebAPI中更新导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!