问题
Problem
I am able to successfully GET the related items from either end of this relationship using the following:
- http://localhost/api/Exercises(1)?$expand=Measurements
- http://localhost:49540/api/Exercises(1)/Measurements
Now I am trying to manage the relationship between them. There are a few examples Ive found out there that Ive tried and none work. Heres one and heres another.
Models
public class Exercise
{
public int Id { get; set; }
public virtual ICollection<Measurement> Measurements { get; set; }
}
public class Measurement
{
public int Id { get; set; }
public virtual ICollection<Exercise> Exercises { get; set; }
}
Actions
Here are the actions I have tried and their requests:
[HttpDelete]
public IHttpActionResult DeleteRef([FromODataUri] int key, [FromODataUri] string relatedKey, string navigationProperty)
{
return StatusCode(HttpStatusCode.NoContent);
}
URL: http://localhost/api/Exercises(1)/Measurements$id=http://localhost/api/Measurements(4)
Result: 404
[HttpDelete]
[ODataRoute("Exercises({key})/Measurements({relatedKey})/$ref")]
public IHttpActionResult DeleteMeasurementFromExercise(int key, int relatedKey)
{
return StatusCode(HttpStatusCode.NoContent);
}
URL: n/a
Result: Server error: The path template 'Exercises({key})/Measurements({relatedKey})/$ref' on the action 'DeleteMeasurementFromExercise' in controller 'Exercises' is not a valid OData path template. The URI segment '$ref' is invalid after the segment 'Measurements({relatedKey})'.
Related
This guy had the same symptoms and was able to resolve it after Microsoft released a fix. I am running with the latest versions of Web API and oData and still have this problem.
<package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net46" />
<package id="Microsoft.AspNet.OData" version="5.9.0" targetFramework="net46" />
<package id="Microsoft.OData.Core" version="6.15.0" targetFramework="net46" />
<package id="Microsoft.OData.Edm" version="6.15.0" targetFramework="net46" />
回答1:
As usual, minutes after posting a question to SO, the answer to the problem Im stuck on for days comes to me.
According to the Deleting a Relationship Between Entities at the bottom of this documentation, my URL should look like this:
DELETE http://host/Suppliers(1)/Products/$ref?$id=http://host/Products(1)
for an action like this:
public IHttpActionResult DeleteRef([FromODataUri] int key, [FromODataUri] string relatedKey, string navigationProperty)
{
return StatusCode(HttpStatusCode.NoContent);
}
The documentation is wrong. After some digging, I found your url should look like this:
DELETE http://host/Suppliers(1)/Products(2)/$ref
来源:https://stackoverflow.com/questions/36678752/web-api-odata-v4-ref-404-or-server-error