Question

I am trying to persist an entity and its related object in an ICollection. Error message is (server name removed):

System.Data.Services.Client.DataServiceRequestException: System.Data.Services.Client.DataServiceClientException: No HTTP resource was found that matches the request URI 'Service.Facade.Reports/odata/Reports(8236)/LayoutData'.
No routing convention was found to select an action for the OData path with template '~/entityset/key/navigation'.

Some test client code:

string uriString = "Service.Facade.Reports/odata/";
Uri uri = new Uri(uriString);
DataServiceContext context = new DataServiceContext(uri, DataServiceProtocolVersion.V3);
var layoutData = new ReportLayoutData { Data = new byte[] { 1, 2, 3 } };
var list = new List<ReportLayoutData>();
list.Add(layoutData);
var report = new ReportLayout { LayoutData = list, Name = "thing" };
context.AddObject("Reports", report);
context.AddRelatedObject(report, "LayoutData", list[0]); //Newly Added for Web API
DataServiceResponse response = context.SaveChanges();

Without the call to AddRelatedObject the service works in adding the Report. But the navigation property is not serialized automatically when I step through the service so that's why I added AddRelatedObject. Previously this same code worked (without AddRelatedObject) with WCF Data Services and I am now trying to convert to Web API.

At the service level it seems I need to add a routing convention which is what I thought this was:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<ReportLayout>("Reports");
    builder.EntitySet<ReportLayoutData>("ReportLayoutData");
    builder.EntitySet<DatabaseInstance>("DataSources");
    builder.EntitySet<DataSourceObject>("DataSourceObject");
    config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

I added this to my controller to support POST / PUT on the navigation property.

// POST PUT odata/Reports(5)/LayoutData
[AcceptVerbs("POST", "PUT")]
public async Task<IHttpActionResult> CreateLink([FromODataUri] int key, string navigationProperty, [FromBody] Uri link)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    ReportLayout report = await db.Reports.FindAsync(key);
    if (report == null)
    {
        return NotFound();
    }

    switch (navigationProperty)
    {
        case "LayoutData":
            string layoutKey = GetKeyFromLinkUri<string>(link);
            ReportLayoutData reportLayout = await db.ReportsData.FindAsync(layoutKey);
            if (reportLayout == null)
            {
                return NotFound();
            }
            report.LayoutData = Enumerable.Range(0,0).Select(x=>reportLayout).ToList();
            await db.SaveChangesAsync();
            return StatusCode(HttpStatusCode.NoContent);

        default:
            return NotFound();
    }
}

// Helper method to extract the key from an OData link URI.
private TKey GetKeyFromLinkUri<TKey>(Uri link)
{
    TKey key = default(TKey);

    // Get the route that was used for this request.
    IHttpRoute route = Request.GetRouteData().Route;

    // Create an equivalent self-hosted route. 
    IHttpRoute newRoute = new HttpRoute(route.RouteTemplate,
        new HttpRouteValueDictionary(route.Defaults),
        new HttpRouteValueDictionary(route.Constraints),
        new HttpRouteValueDictionary(route.DataTokens), route.Handler);

    // Create a fake GET request for the link URI.
    var tmpRequest = new HttpRequestMessage(HttpMethod.Get, link);

    // Send this request through the routing process.
    var routeData = newRoute.GetRouteData(
        Request.GetConfiguration().VirtualPathRoot, tmpRequest);

    // If the GET request matches the route, use the path segments to find the key.
    if (routeData != null)
    {
        ODataPath path = tmpRequest.GetODataPath();
        var segment = path.Segments.OfType<KeyValuePathSegment>().FirstOrDefault();
        if (segment != null)
        {
            // Convert the segment into the key type.
            key = (TKey)ODataUriUtils.ConvertFromUriLiteral(
                segment.Value, ODataVersion.V3);
        }
    }
    return key;
}

POCOs used

[Serializable]
public partial class ReportLayout
{
public const string DefaultName = "Report...";
public const string DefaultGroup = "Uncategorized";

public ReportLayout()
{
    LayoutData = new List<ReportLayoutData>();
    Name = DefaultName;
    Group = DefaultGroup;
    UserDefinedQuery = false;
}

public virtual DatabaseInstance DatabaseInstance { get; set; }
public virtual ICollection<ReportLayoutData> LayoutData { get; set; }
public string Name { get; set; }
public string Group { get; set; }
public int ReportLayoutID { get; set; }
public string Query { get; set; }
public bool UserDefinedQuery { get; set; }

public void SetData(byte[] data)
{
    if (LayoutData.Count() > 0)
    {
        LayoutData.ElementAt(0).Data = data;
    }
    else
    {
        LayoutData.Add(new ReportLayoutData() {Data = data});
    }
}
}

[Serializable]
public class ReportLayoutData
{
    public byte[] Data { get; set; }
    public virtual ReportLayout ReportLayout { get; set; }
    public int ReportLayoutDataID { get; set; }
}
Was it helpful?

Solution

Turns out I was almost right but had made a couple of stupid mistakes server side and the client side code needed to be altered too.

Server side fixes within the CreateLink action:

  • report.LayoutData = Enumerable.Range(0,0).Select(x=>reportLayout).ToList(); => report.LayoutData = Enumerable.Range(0,1).Select(x=>reportLayout).ToList(); Jeez doofus!

  • string layoutKey = GetKeyFromLinkUri<string>(link); => int layoutKey = GetKeyFromLinkUri<int>(link);

Client side code changed as well to nudge the DataServiceContext to do the right thing:

context.AddObject("Reports", report);
context.AddObject("ReportLayoutData", layoutData);
context.AddLink(report, "LayoutData", layoutData);

The above DataServicecontext setup translates into calls to:

 // POST odata/Reports
 public async Task<IHttpActionResult> Post(ReportLayout reportlayout)

 // POST PUT odata/Reports(5)/LayoutData
 [AcceptVerbs("POST", "PUT")]
 public async Task<IHttpActionResult> CreateLink([FromODataUri] int key, string navigationProperty, [FromBody] Uri link)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top