Search code examples
odataodatalib

How to create ODataNavigationLink when using ODataLib entry writer?


I am trying to find an example of how to properly instantiate ODataNavigationLink in case it's non-empty. The only code example I've found creates a non-expanded link but doesn't bind it to any data:

//create a non-expanded link for the orders navigation property
  writer.WriteStart(new ODataNavigationLink()
  {
      IsCollection = true,
      Name = "Orders",
      Url = new Uri("http://microsoft.com/Customer(" + 
                 dataSource.Customers.First().CustomerID + ")/Orders")
  });
  writer.WriteEnd(); //ends the orders link

So here we specify the link to "Orders". But how do I provide the actual values for the link (in this example the link is a collection but it can also be a single entry). When I was writing the payload manually I was providing "href" attribute with a linked entry ID. I can't figure out how this is done with ODataLib.


Solution

  • The value appear in the 'href' attribute just shows the Url property of ODataNavigationLink, so you can try the following code to set it manually:

    //create a non-expanded link for the orders navigation property
    writer.WriteStart(new ODataNavigationLink() { 
        IsCollection = true,
        Name = "Orders",
        Url = new Uri("http://microsoft.com/Orders(3)") }); 
    writer.WriteEnd(); //ends the orders link
    

    In common, the navigation link should be the source entity url followed by the navigation property,see here, while id should point to the real entry ID.

    updated:

    According to the latest feedback, you're trying to write the 'Collection of links' as described in section 14.1 of the atom spec. Thus you can try ODataEntityReferenceLinks class:

    var referenceLink1 = new ODataEntityReferenceLink { Url = new Uri("http://host/Orders(1)") };
    var referenceLink2 = new ODataEntityReferenceLink { Url = new Uri("http://host/Orders(2)") };
    var referenceLink3 = new ODataEntityReferenceLink { Url = new Uri("http://host/Orders(3)") };
    var referenceLinks = new ODataEntityReferenceLinks
    {
        Links = new[] { referenceLink1, referenceLink2, referenceLink3 }
    };
    writer.WriteEntityReferenceLinks(referenceLinks);
    

    and the payload would be something like:

    <links xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">
      <uri>http://host/Orders(1)</uri>
      <uri>http://host/Orders(2)</uri>
      <uri>http://host/Orders(3)</uri>
    </links>