Skip to content

Linking and unlinking entries

object edited this page Feb 12, 2013 · 21 revisions

Link a product to a category

var category = client
    .For("Categories")
    .Set(new { CategoryName = "Test1" })
    .InsertEntry();
var product = client
    .For("Products")
    .Set(new { ProductName = "Test2" })
    .InsertEntry();

client
    .For("Products")
    .Key(product)
    .LinkEntry("Category", category);

Request URI: PUT Products(79)/$links/Category
Request content:

<uri xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">Categories(10)</uri>

Link a product to a different category

var category = client
    .For("Categories")
    .Set(new { CategoryName = "Test1" })
    .InsertEntry();
var product = client
    .For("Products")
    .Set(new { ProductName = "Test2", CategoryID = 1 })
    .InsertEntry();

client
    .For("Products")
    .Key(product)
    .LinkEntry("Category", category);

Request URI: PUT Products(80)/$links/Category
Request content:

<uri xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">Categories(11)</uri>

Unlink a product from a category

var category = client
    .For("Categories")
    .Set(new { CategoryName = "Test6" })
    .InsertEntry();
var product = client
    .For("Products")
    .Set(new { ProductName = "Test7", Category = category })
    .InsertEntry();

client
    .For("Products")
    .Key(product)
    .UnlinkEntry("Category");

Request URI: DELETE Products(81)/$links/Category


Link a category to multiple products

var category = client
    .For("Categories")
    .Set(new { CategoryName = "Test3" })
    .InsertEntry();
var product1 = client
    .For("Products")
    .Set(new { ProductName = "Test4", UnitPrice = 21m, CategoryID = 1 })
    .InsertEntry();
var product2 = client
    .For("Products")
    .Set(new { ProductName = "Test5", UnitPrice = 22m, CategoryID = 1 })
    .InsertEntry();

client
    .For("Categories")
    .Key(category)
    .LinkEntry("Products", new[] { product1, product2 });

Request URI: MERGE Categories(13)/$links/Products
Request content:

<entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
  <title />
  <updated>2012-10-15T14:45:21.7200000Z</updated>
  <author>
    <name />
  </author>
  <id />
  <content type="application/xml">
    <m:properties />
  </content>
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Products" type="application/atom+xml;type=Entry" title="Products" href="Products(110)" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Products" type="application/atom+xml;type=Entry" title="Products" href="Products(111)" />
</entry>

See also:
Adding entries with links
Updating entries with links
Modifying data