Quantcast
Channel: ASP.NET MVC / Web API / Web Pages
Viewing all articles
Browse latest Browse all 7925

New Post: OData Entity Creation with Navigation Properties

$
0
0
If I have a model as such:
public class Customer
{
  public int Id { get; set; };
  public ICollection<Order> Orders { get; set; };
}

public class Order
{
  public int Id { get; set; };
  public string Name { get; set; }
  
  [Required]
  public Customer Customer { get; set; }
}
Is there any way I can create a new Order object with a single OData POST request, where Customer is an existing object?

With Web API 2 Release Candidate I have attempted to submit the following POST but on the Web API EntitySetController, the bound Entity passed to CreateEntity virtual method is null when I submit this (I have also expanded the __metadata object to include id = uri and the type with no success):
{
  "Name":"MyTestOrder",
  "Customer":
   {
      "__metadata":
      { 
         "uri":"http://localhost/odata/Customers(10)"
      }
   }
}
I also tried using WCF Data Services Client with following code:
var customer = ctx.Customers.Where(c => c.Id == 10).SingleOrDefault();
var newOrder = new Order { Name = "TestOrder", Customer = customer };
ctx.AddToOrders(newOrder);
ctx.AddLink(customer, "Orders", newOrder);
ctx.SetLink(newOrder, "Customer", customer);
ctx.SaveChanges();
This generates the following JSON in a single POST request:
{
  "odata.type":"MyModel.Order",
  "Customer@odata.bind":"http://localhost/odata/Customers(10)",
  "Id":0,
  "Name":"Test Order"
}
But on the Web API side, again the model binding passes null into the CreateEntity(TEntity entity) method on the EntitySetController.

I realize I could expose the Foreign Key property on the Order entity, but this kind of goes against the principles of HATEOAS.

So I'd like to know if I can do it by including a navigation link in the POST request.

Viewing all articles
Browse latest Browse all 7925

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>