3

I must update my entity with its children list as shown here:

 public class Entity1 
 { 
    int Id{get;set;} 
    ObservableCollection<Child1> ChildrenList {get;set;} 
    string Name{get;set;}
 }

public class Child1
{
    string Nome{get;set;}
    string Cognome {get;set;}
}

I implemented patch method in this way:

[AcceptVerbs("PATCH", "MERGE")]
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Entity1> entityDelta)
{

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var entity = await Context.Entity1.FindAsync(key);
            if (entity == null)
            {
                return NotFound();
            }
            entityDelta.Patch(entity);

            try
            {
                await Context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                return NotFound();
            }
            return Updated(entity);
}

but when I try to call it from fiddler in this way:

Url: http://localhost/odata4/Entity1(1)/  with patch request

Request Headers: Content-Type: application/json

Request Body: 
{
Name: "pippo2",
ChildrenList:[{
Nome: "Test",
Cognome: "Pippo"
}]
}

It gives an error in Model.isValid Property and specified return this error:

Cannot apply PATCH to navigation property 'ChildrenList' on entity type 'Entity1'.

How can I solve it? Is the patch method the correct method to use?

TomDoesCode
  • 3,580
  • 2
  • 18
  • 34
axa82
  • 33
  • 1
  • 6

1 Answers1

7

OData V4 spec says for update an entity:

The entity MUST NOT contain related entities as inline content. It MAY contain binding information for navigation properties. For single-valued navigation properties this replaces the relationship. For collection-valued navigation properties this adds to the relationship.

So, You can use:

  1. Update the child:

    Patch/Put: ~/Child1s(...)

  2. Update parent

    Patch/Put: ~/Entity1s(...)

  3. Update the relateship between parent and child:

    PATCH/PUT ~/Entity1s(...)/ChildrenList/$ref

with entity reference links content.

Sam Xu
  • 3,264
  • 1
  • 12
  • 17
  • How can i try it in Fiddler? What's the request body for Content-type: application/json ? I try with this but fail: `{ ChildrenList: [{ "uri": "http://localhost/odata4/ChildrenList(1)"}] }` – axa82 Sep 15 '15 at 16:16
  • There's a test case that you can refer to: https://github.com/OData/WebApi/blob/master/OData/test/E2ETest/WebStack.QA.Test.OData/Singleton/SingletonTest.cs#L271-L277 The related controller is https://github.com/OData/WebApi/blob/master/OData/test/E2ETest/WebStack.QA.Test.OData/Singleton/PartnersController.cs#L69-L92 – Sam Xu Sep 23 '15 at 03:24